Login

Tag "url"

Snippet List

Yet another query string template tag

This one works works with or without query string dicts defined in the context. And it handles replacement, addition and removal of values for parameters with multiple values. Usage: {% url view %}{% query_string qs tag+tags month=m %} where `view`, `qs` (dict), `tags` (list of strings) and `m` (number) are defined in the context. Full detail in the doc string.

  • url
  • template-tag
  • query-string
Read More

Querystring Builder - create urls with GET params

Save the code as app_name/templatetags/urlbuilder.py. Supply your view with a dictionary of "default" query params, likely taken from the request. Then, in the template: `{% load urlbuilder %} {% url some-url as base_url %}` That sets you up. Then you can make links. For example: <th><a href="{% build_url base_url query_params sort=name %}">Name</a></th> Say query_params has: page: 2, filter: active, sort: id The above tag would spit out /base/url?page=2&filter=active&sort=name The tag also has support for using a variable as the replacement key. Say "filter_key" is a variable available to the template with the value "filter": {% build_url base_url query_params filter_key default %} Using the above example, that would output /base/url?page=2&filter=default&sort=id

  • tag
  • templatetag
  • url
  • parameter
  • querystring
  • GET
  • param
Read More

Automatic CRUD urls from your models...

Just extends your models from this One... is abstract so, it will not generate a table. Now, in your urls.py do this: from django.conf.urls.defaults import * from animals.models import Dog, Cat, Bird urlpatterns = patterns('animals.views', url(r'^$', 'index', {},Dog._meta.app_label), ) dog=Dog() cat=Cat() bird=Bird() urlpatterns+=dog.build_generic_CRUD_urls(Dog) urlpatterns+=cat.build_generic_CRUD_urls(Cat) urlpatterns+=bird.build_generic_CRUD_urls(Bird) then you can create the templates, and get the urls like this: {{ object.get_absolute_url }} View {{ object.get_update_url }} Edit {{ object.get_delete_url }} Delete {{ dummy_object.get_create_url }} Create dummy_object is a quick and dirty solution until I find some better... With all these you can create 54 functional and low detail CRUDS in one hour. :D Enjoy!

  • model
  • url
  • generation
Read More

Resolve URLs to view name and args/kwargs

This is an expanded version of ["Resolve URLs to view name"](http://djangosnippets.org/snippets/1378/) without the monkey-patching. Simply pass in a URL such as '/events/rsvp/some_conference/' and you'll get back the view name or function (if name isn't available) and the arguments to it, eg 'events_rsvp', [], {'event_slug':'some_conference'}. Example (blatantly copied from previous snippet): === urlconf ==== urlpatterns = patterns('' (r'/some/url', 'app.views.view'), url(r'/some/other/(?P<url>\w+)', 'app.views.other.view', name='this_is_a_named_view'), url(r'/yet/another/(?P<url>\w+)/(\d+)', 'app.views.yetanother.view', name='one_with_args'), ) === example usage in interpreter === >>> from some.where import resolve_to_name >>> print resolve_to_name('/some/url') ('app.views.view',[],{}) >>> print resolve_to_name('/some/other/url') ('this_is_a_named_view',[],{'url':'url'}) >>> print resolve_to_name('/yet/another/url/5') ('one_with_args',[5],{'url':'url'}) From [fahhem.com](http://fahhem.com/) and [Recrec Labs](http://recreclabs.com/)

  • url
  • resolve
  • name
  • args
  • kwargs
Read More

Manipulate URL query strings using context variables using a template tag

A template tag that includes a modified version of the GET query string. the query string can be manipulated by adding and removing fields. If a value is given that resolves to a context variable that the value of the variable is used. Based on [this snippet by dnordberg](http://djangosnippets.org/snippets/826/), but with the ability to use context and done in a cleaner manner, without the need to add an arbitrary template.

  • url
  • template-tag
  • query-string
Read More

Middleware to resolve current URL to module and view

Add it to MIDDLEWARE_CLASSES and you will get request.current_view getting values like "connection.views.index" or "django.views.static.serve" - one example usage is to show different help text based on current view name. EDIT: actually, you can use process_view middleware function where you automatically get current_view as first parameter.

  • middleware
  • view
  • url
  • resolve
Read More

django subdomain support for both resolve and reverse.

Add these two middleware to the top of MIDDLEWARE_CLASSES. Add BASE_DOMAIN to your setting file : BASE_DOMAIN = '.13.com'. your root urlconf may like this: urlpatterns = patterns('', url(r'^www:(?P<id>[0-9]+)/$', 'couponcn.store.views.site_index', name='site_index'), url(r'^news:abc/def/$', 'couponcn.store.views.site_index', name='site_index2'), ) then {% url site_index id=4 %}<br /> {% url site_index2 %} in your template or the reverse function will work out urls like this: http://www.13.com/4/ http://news.13.com/abc/def/

  • url
  • reverse
  • resolve
  • subdomain
Read More

Publishing service endpoint uri to javascript

My application is made up of two main pieces: 1) an ajax client, and 2) backend services supplying data to the ajax client. Django delivers html files that bootstrap the javascript client, which in turns calls back to Django's restful services. Most of javascript code is in static .js files that being delivered to the browser bypassing Django. When calling back into Django, I started by embedding call endpoints into the javascript code. Soon, I noticed, though, that every time I adjusted an endpoint's url in urls.py, I also had to remember to go back and adjust the javascript. This was suboptimal and violated the DRY principle. I realized that all the information I needed was already in urls.py. All that needed to be done, was to find a way to expose that information to the javascript environment. The code I'm including does exactly that. It consists of two pieces: a view function and a corresponding javascript template. The view function will go through all declared urls looking for those whose name ends with '-svc'. These urls are then converted into javascript constants by the template. The url names are slightly mangled to conform to javascript identifier conventions and if you have any url parameters, they will be encoded into something that javascript can easily replace with real values at run time. For example, `url('^blog/(?P<id>[\d]+/$', 'sample.views.showblog', name='blog-entry')` will become `svc.__BLOG_ENTRY = "/blog/{id}/"` to get the uri from your javascript code, you simply make this call: `svc('BLOG_ENTRY', {id: 12345})` and you'll get back `/blog/12345/` Requirements: the javascript template assumes availability of the Namespace library by Maxime Bouroumeau-Fuseau (http://code.google.com/p/namespacedotjs/)

  • javascript
  • urls
  • url
  • service
  • endpoint
Read More

RedirectedURLField

This field is similar to the standard URLField, except it checks the given URL for a HTTP 301 response (permanent redirect) and updates its value accordingly. For example: >>> url = RedirectedURLField() >>> url.clean('http://www.twitter.com/') >>> 'http://twitter.com/' In models: class TestModel(models.Model): url1 = RedirectedURLField('Redirected URL') url2 = models.URLField('Standard URL')

  • url
  • redirect
  • field
Read More

Get admin url for a model

Add this to your model to be able to get their admin change link from anywhere Useful if you want to jump to the admin screen of an object you are looking at on the front end

  • admin
  • url
Read More

Reliably create a Django File using the contents of a URL

There's no direct way to save the contents of a URL to a Django File field: you're required to use a File instance but those can only safely wrap normal files, not the file-like object returned by urllib2.urlopen. Several examples online use urllib.urlretrieve() which creates a temporary file but performs no error handling without writing a ton of hackish code. This demonstrates how to create a NamedTemporaryFile, fill it with the URL contents and save it, all using APIs which raise exceptions on errors.

  • url
  • filefield
  • file
  • urlopen
Read More

Simple views dispatcher by http methods

Calls a view by request.method value. To use this dispatcher write your urls.py like this: urlpatterns = pattern('', url(r'^foo/$', dispatch(head=callable1, get=callable2, delete=callable3)), ) If `request.method` is equal to head, `callable1` will be called as your usual view function; if it is `get`, `callable2` will be called; et cetera. If the method specified in request.method is not one handled by `dispatch(..)`, `HttpResponseNotAllowed` is returned.

  • urls
  • rest
  • http
  • url
Read More

URL models

You can use `UrlModel` to provide URL functionality to any instance of any model and any language (language support can be removed from this). Each model must have own view method, that returns HttpResponse. I was inspired by Flatpages. It is useful for small sites and static pages. `class Page(UrlModel): text = models.TextField() def view(self, request) # do something here return HttpResponse(...)`

  • middleware
  • urls
  • models
  • foreignkey
  • model
  • generic
  • url
  • foreign-key
  • genericforeignkey
  • contenttypes
  • 404
  • contenttype
  • content-type
Read More

71 snippets posted so far.