CRUD pattern for urls.py, passing object from URI to view

crud, django, generics, view

Solution

Yes, you can do this, and I've done it. The Django generic views don't support it directly. You need to wrap the generic view with your own view that looks up the model and constructs the queryset. Here's an example (showing only the detail view, you can do the others similarly). I've changed your named patterns in the URLconf to use "model" instead of "object", which is clearer naming:

in urls.py:

url(r'^(?P<model>\w+)/(?P<object_id>\d+)/$', 'my_app.views.my_object_detail',  name='object_detail'),

in my_app/views.py

from django.views.generic.list_detail import object_detail
from django.db.models.loading import get_model
from django.http import Http404

def get_model_or_404(app, model):
    model = get_model(app, model)
    if model is None:
        raise Http404
    return model

def my_object_detail(request, model, object_id):
    model_class = get_model_or_404('my_app', model)
    queryset = model_class.objects.all()
    return object_detail(request, queryset, object_id=object_id)

If you're clever and want to keep things as DRY as possible, you could create a single wrapper that accepts the generic view function to call as one of its arguments, rather than having a wrapper for create, a wrapper for update, etc.

Problem

Can the object value be looked up and passed to the generic view? Would the generic views need to be moved to views.py in order to support the object lookup? urls.py ``` urlpatterns = patterns('myapp.views', url(r'^mymodel/create/$', view='mymodel_create', name='mymodel_create'), ) urlpatterns += patterns('django.views.generic', url(r'^(?P<model>\w+)/create/$','create_update.create_object', name='object_create'), url(r'^(?P<model>\w+)/(?P<id>\d+)/update/$', 'create_update.update_object', name='object_update' ), url(r'^(?P<model>\w+)/(?P<id>\d+)/delete/$', 'create_update.delete_object', name='object_delete'), url(r'^(?P<model>\w+)/(?P<object_id>\d+)/$', 'list_detail.object_detail', name='object_detail'), url(r'^(?P<model>\w+)/$','list_detail.object_list', name='object_list'),' ) ``` Example URL's: ``` http://localhost/myapp/thing/create http://localhost/myapp/thing/1 http://localhost/myapp/thing/1/update http://localhost/myapp/thing/1/delete ``` I'd like to use (?P\w+) to find the corresponding Model, 'Thing', but when this code is executed, the following error occurs: object_list() got an unexpected keyword argument 'model'

Original source