Previous Page Next Page

Limiting Access to Generic Views

Limiting access to generic views is a bit different from limiting access to your own views, because there is no view code in which to verify permissions and authentication. Generic views do use a RequestObject, so you can access authentication and permissions in the template file of the generic view. However, if you want to limit access before the template gets called, you must create your own wrapper view that handles authentication and password verification.

To create a wrapper, you modify the URLconf file and add another pattern to the wrapper view function. Then you create the wrapper view function in the application's views.py file. The wrapper view function only needs to verify the permissions and/or authentication and then return the generic view function with arguments and keywords passed through. For example, the following URL pattern links to a generic object_details view:

(r'^/obj_details/(?P<object_id>\d+)/$', object_detail, obj_info),

To implement a wrapper function called secure_object_detail(), modify the entry as shown in the following URL pattern:

(r'^/obj_details/(?P<object_id>\d+)/$', site.Obj.secure_object_detail, obj_info),


					  

You then add the following code snippet to the application's views.py file. This code imports the object_detail() generic view and defines a wrapper view, secure_object_detail(), that verifies that the user is logged in before calling the generic object_view() function:

from django.views.generic.list_detail import object_detail
@login_required
def secure_object_detail(*args, **kwargs):
    return object_detail(*args, **kwargs)

Previous Page Next Page