This is a simple example that shows how to convert the object_detail
generic view to the class based DetailView
.
Before:
@permission_required('b2c.view_b2ctrack') def view_track(request,id): return object_detail(request, queryset=B2CTrack.objects.all(), object_id=id, template_name='track_detail.html')
After:
class TrackDetailView(DetailView): template_name = 'track_detail.html' model = B2CTrack ## Override dispatch to apply the permission decorator @method_decorator(permission_required('b2c.view_b2ctrack')) def dispatch(self, *args, **kwargs): return super(TrackDetailView, self).dispatch(*args, **kwargs)
Only odd thing I encountered was that the new View wants to see the ID of the object named ‘pk’, instead of ‘id’ that I was using. The DEV branch of Django includes the pk_url_kwarg
variable that allows a rename, but it isn’t available in v1.3.
Note that I could have used queryset
instead of model
to specify the data source. Either will give the same result in this example.