0

Good day,

I have the following in my URLConf:

from django.contrib.auth.decorators import user_passes_test

urlpatterns = patterns('',
    (r'^manage/(?P<pk>\d+)/$', user_passes_test(lambda u: (u.is_authenticated()))
    UpdateView.as_view(model=Organization, success_url="/organizations/updated/", template_name="organization/manage.html",))),

So only authenticated users can access the view functionality via the url.

Question: Except for sub-classing the generic view, is there a way to inspect the pk embedded in the URL? I'd like to further validate that the user trying to access the Update function has the required permission.

The documentation doesn't go into this detail, and I'm battling to find any other reference to it.

Siphiwe Gwebu
  • 529
  • 1
  • 5
  • 13

2 Answers2

0

If you're looking to extend the default functionality, especially if it's with something as delicate as user permission, the only real option is to subclass. I've turned to subclassing all my views, even when all the class definition has is a template_name, because it's much simpler to extend later.

Subclassing gives you full control over your code. There is no need to override crucial methods like get() orpost(), though -- auxiliary stuff like get_context_data() or form_valid() can take care of most checks and validations you need.

Berislav Lopac
  • 16,656
  • 6
  • 71
  • 80
0

Yes there is, you just have to get more familiar with python decorators:

def my_custom_check(view):
  def view_wrap(request, *args, **kwargs):
    pk = kwargs['pk']
    # do your check here
    return view(request, *args, **kwargs)
  return view_wrap

Use it like this:

(r'^manage/(?P<pk>\d+)/$', my_custom_check(UpdateView.as_view(model=Organization, ...))),
  • Seems like the way to go about it (and a generally good tool to have in my toolbox!). Could u recommend any particular book/documentation link? I have looked at links such as [this](http://stackoverflow.com/questions/739654/understanding-python-decorators) and [this](http://docs.python.org/reference/compound_stmts.html#function) but I still don't feel solid on decorators. K, I wanted to vote up your answer but I need 15 reputation, which is more than am worth right now, sorry... – Siphiwe Gwebu May 30 '12 at 06:23
  • http://www.artima.com/weblogs/viewpost.jsp?thread=240808 is imo quite good, although I am sure there are more out there ;) – Florian Apolloner May 30 '12 at 09:13