Changes between Initial Version and Version 1 of GenerateGenericURLs


Ignore:
Timestamp:
Jun 22, 2006, 6:34:50 PM (18 years ago)
Author:
Jon Dugan <jdugan@…>
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • GenerateGenericURLs

    v1 v1  
     1Here's a little function I wrote to generate a standard set of URL mappings I use with generic views.  It takes a list of tuples that each contain the name to use for the url and the model class that represents it.  This function generates generic views for listing, viewing details, adding, editing and deleting objects for the given model. For example:
     2
     3{{{
     4make_url_list([('widget', Widget)])
     5}}}
     6
     7will create:
     8
     9{{{
     10^/widget/$  -- will list all widgets
     11^/widget/(?<object_id>\d+)/$ -- will give details for a specific object
     12^/widget/edit/(?<object_id>\d+)/$ -- will edit an object
     13^/widget/delete/(?<object_id>\d+)/$ -- will delete an object
     14^/widget/edit/$ -- will add an object
     15}}}
     16
     17Here's the function:
     18
     19{{{
     20def make_url_list(input, prefix=''):
     21    l = []
     22
     23    for (name, model) in input:
     24        l.append((r'^%s/$' % name,
     25            'django.views.generic.list_detail.object_list',
     26            dict(queryset=model.objects.all(), allow_empty=True)))
     27
     28        l.append( (r'^%s/(?P<object_id>\d+)/$' %name,
     29            'django.views.generic.list_detail.object_detail',
     30            dict(queryset=model.objects.all())))
     31
     32        l.append( (r'^%s/add/$' % name,
     33            'django.views.generic.create_update.create_object',
     34            dict(model=model,
     35                post_save_redirect='%s/%s/%s/' % (prefix, name, '%(id)s'))))
     36
     37        l.append( (r'^%s/edit/(?P<object_id>\d+)/$' % name,
     38            'django.views.generic.create_update.update_object',
     39            dict(model=model,
     40                post_save_redirect='%s/%s/%s/' % (prefix, name, '%(id)s'))))
     41
     42        l.append( (r'^%s/delete/(?P<object_id>\d+)/$' % name,
     43            'django.views.generic.create_update.delete_object',
     44            dict(model=model,
     45                post_delete_redirect='%s/%s/' % (prefix, name))))
     46}}}
     47
     48This function could be generalized a bit more, but I've found it handy as is.  I use it in my urls.py like this:
     49
     50{{{
     51tup = tuple(make_url_list(input,prefix='/prefix_if_needed'))
     52
     53urlpatterns = patterns('',
     54    (r'^someotherurl/$', 'some.other.package'),
     55    *tup)
     56}}}
Back to Top