views:

396

answers:

2

I have a situation that requires redirecting users who are already logged in away from the login page to another page. I have seen mention that this can be accomplished with decorators which makes sense, but I am fairly new to using them. However, I am using the django login and a third party view (from django-registration). I do not want to change any of the code in django.contrib.auth or django-registration. How can I apply a decorator to a view that is not to be modified in order to get the desired behavior.

Thanks in advance!

UPDATE: I discovered that I mistakenly associated the login function with the registration module. django-registration has nothing to do with this issue. However, I still need to be able to override default login() behavior. Any thoughts?

+2  A: 

If you have the decorator function and you know which view in django-registration you want to decorate, you could just do

registration.view_func = decorator_func(registration.view_func)

where registration is the module in django-registration which contains the view function you want to decorate, view_func is the view function you want to decorate, and decorator_func is the decorator.

Vinay Sajip
But which is the best file to do this in? ;)
kaleissin
+3  A: 

Three more ways to do it, though you'll need to use your own urlconf for these:

  1. Add the decorator to the view directly in the urlconf:

    ...
    (regexp, decorator(view)),
    ...
    

    You need to import the view and the decorator into the urlconf though, which is why I don't like this one. I prefer to have as few imports in my urls.py's as possible.

  2. Import the view into an <app>/views.py and add the decorator there:

    import view
    
    
    view = decorator(view)
    

    Pretty much like Vinay's method though more explicit since you need an urlconf for it.

  3. Wrap the view in a new view:

    import view
    
    
    @decorator
    def wrapperview(request, *args, **kwargs):
        ... other stuff ...
        return view(request, *args, **kwargs)
    

    The last one is very handy when you need to change generic views. This is what I often end up doing anyway.

Whenever you use an urlconf, order of patterns matter, so you might need to shuffle around on which pattern gets called first.

kaleissin
Just what the doctor ordered - #3. Nice job.
Andrew Sledge