Login

Tag "urls"

Snippet List

Controller Class for Views

I wanted to be able to share common code among a subset of views without copy-and-pasting the code or the same function into each view, so I decided to wrap a class around the views so that the common code (i.e. loading a model that each of the views would affect) can go in the __init__ of that class. I created the controller_view function above to allow the urls to access those class methods. It would be called something like this: url(r'^someview$', controller_view(SomeController, 'someview'), name='someview'), Where the SomeController inherits (or is structured like) the Controller class above and implements __init__ and someview as methods. I'm new to Django so it's entirely possible I've missed something that already does this or that makes this unnecessary. If so, let me know so that I can figure out how to do this right, otherwise, hopefully this is helpful to someone else out there.

  • urls
  • views
Read More

Routing urls.py By Convention

No more entries in urls.py... This is the simple version of a central controller for an app that routes requests by names, thus keeping you from adding a line into urls.py for every, single, page. Assuming your app name is "account", add the following to your urls.py file: (r'^account/(?P<path>.*)\.dj(?P<urlparams>/.*)?$', 'account.views.route_request' ) The URL /account/mypage.dj will be routed directly to account.views.py -> process_request__mypage(request, parameters). You can read more about this on [my blog](http://warp.byu.edu/site/content/1100).

  • urls
  • routing
Read More

Decorate every view in a url tree

Add login_required (or any other combination of decorators) to any view references by the urls created by patterns(...). My personal little itch as an example... urlpatterns += required( login_required, patterns('', (r'^api/', include(api.urls)), ) )

  • urls
  • login_required
Read More

Automatically create urls for templates in a directory

When developing a site, I sometimes want to be able to visually reference the HTML before it's given a real context, and a view. This extra bit of code will allow you to add a directory within your templates dir, and pull any html files and subdirectories from it. I added the if statement to automatically use an index.html file if there's no file and extension at the end. You can substitute anything you like for the "html" in "(?P<base>html)". That's just passed as an argument to prepend to the template as a base directory for the templates.

  • urls
  • templates
  • direct_to_template
Read More

Decorating URL includes

Apply a decorator to every urlpattern and URLconf module returned by Django's include() method . This allows you use a decorator on any number of views without having to decorate each one individually. The use case here is wrapping all of the Django Admin with a superuser decorator. This is code that's better left alone where we can't actually go in and decorate the Admin views and urlpatterns manually. It's also almost guaranteed the Admin will include() other URL files. So the added bonus is all the INSTALLED_APPS that have their admin.py files registered by admin.autodiscover() will be decorated automatically as well. This snippet is greatly inspired by [@miracle2k](http://djangosnippets.org/users/miracle2k/)'s excellent [#532](http://djangosnippets.org/snippets/532/). In the comments there @timbroder offers a modification to decorate includes but I think this is cleaner, simpler code and not subject to changes in the Django base code driving _get_url_patterns().

  • urls
  • urlconf
  • decorator
  • urlpatterns
  • resolve
Read More

Generic object_detail view filterable by multiple url values

This view acts as an extension to the object_detail generic view in django.views.generic.object_list. The standard generic view can only filter the queryset by object_id or slug; this view allows you to filter by any parameter you like, as well as multiple parameters. The usage is the same as the standard object_detail view except that you must also give the parameter 'filters', which should be an array of what you would like to filter the url values as, and instead of 'slug' or 'object_id' as the regex parameter in the URL, use 'value1', 'value2', etc. Example: If you have a list of companies, each with multiple branches, you may want a branch details page. A URL for this may look as follows: http://www.mysite.com/company/company-slug/branch-slug/. To implement this simply use the urlpattern example give,

  • filter
  • urls
  • generic-views
  • generic-view
  • filterable
Read More

Automatic urls for static pages

Create in your template dir html files named example.static.html and with this snippet you can get the static page with the url /example/. If you put static file in a sub-directory, the url will be /sub-directory/example/ **Example:** `static_urls = StaticUrls()` `urlpatterns = patterns('', *static_urls.discover())` `urlpatterns += patterns('',` `(r'^admin/doc/', include('django.contrib.admindocs.urls')),` `(r'^admin/', include(admin.site.urls)),` `)`

  • urls
  • static
  • static files
  • url pattern
Read More

Allow any view (probably a generic view) to accept captured URL variables into extra_context.

If your URL pattern looks like: `urlpatterns = patterns('django.views.generic.create_update', url(r'^obj/(?P<obj_id>\d+)/new_thing$', create_object, {'form_class': ThingForm, 'template_name': 'thing/new_thing.html', extra_context: {:this":"that"}), )` You will receive an error, because the create_update view doesn't have a parameter called "obj_id". Supposing you want that variable in the URL, and furthermore let's say you wanted to do something with it in the template. With this function, you can wrap the view, and add the parameter capture_to_context, which maps URL variables to template variables: `urlpatterns = patterns('django.views.generic.create_update', url(r'^obj/(?P<obj_id>\d+)/new_thing$', view_url_vars_to_context(create_object), {'form_class': ThingForm, 'template_name': 'thing/new_thing.html', 'url_vars_to_context':{'obj_id':'objID'}, extra_context: {:this":"that"}}), )` Now objID will be a variable in your template, with the value given to obj_id. This is good for generic views, but there's no reason you couldn't use it for your own views if you really wanted, as long as you had an "extra_context" parameter.

  • urls
  • views
Read More

Conditional url pattern include

if_installed checks to see if the app is in installed apps. If it is not then it excludes it from being resolved in the url structure. In this example, myapp.urls will not be imported if myapp is not installed

  • urls
  • resolver
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

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

29 snippets posted so far.