Code


Version 2 (modified by Jon Dugan <jdugan@…>, 8 years ago) (diff)

--

Here'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:

make_url_list([('widget', Widget)])

will create:

^/widget/$  -- will list all widgets
^/widget/(?<object_id>\d+)/$ # will give details for a specific object
^/widget/edit/(?<object_id>\d+)/$ # will edit an object
^/widget/delete/(?<object_id>\d+)/$ # will delete an object
^/widget/add/$ # will add an object

Here's the function:

def make_url_list(input, prefix=''):
    l = []

    for (name, model) in input:
        l.append((r'^%s/$' % name,
            'django.views.generic.list_detail.object_list',
            dict(queryset=model.objects.all(), allow_empty=True)))

        l.append( (r'^%s/(?P<object_id>\d+)/$' %name,
            'django.views.generic.list_detail.object_detail',
            dict(queryset=model.objects.all())))

        l.append( (r'^%s/add/$' % name,
            'django.views.generic.create_update.create_object',
            dict(model=model,
                post_save_redirect='%s/%s/%s/' % (prefix, name, '%(id)s'))))

        l.append( (r'^%s/edit/(?P<object_id>\d+)/$' % name,
            'django.views.generic.create_update.update_object',
            dict(model=model,
                post_save_redirect='%s/%s/%s/' % (prefix, name, '%(id)s'))))

        l.append( (r'^%s/delete/(?P<object_id>\d+)/$' % name,
            'django.views.generic.create_update.delete_object',
            dict(model=model,
                post_delete_redirect='%s/%s/' % (prefix, name))))

This function could be generalized a bit more, but I've found it handy as is. I use it in my urls.py like this:

tup = tuple(make_url_list(input,prefix='/prefix_if_needed'))

urlpatterns = patterns('',
    (r'^someotherurl/$', 'some.other.package'),
    *tup)