views:

38

answers:

2

Could someone show me how i could write a login decorator like @redirect_to_home for my views so that it modifies the request.PATH variable to a new a value like / whenever it is applied to a view.

I've seen people do quite complex stuff with decorators: I'm yet to figure them out thoroughly.

Thanks

+3  A: 

The best way to start is to understand the login decorator from the django project ( auth module ): http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/decorators.py#L33

If you look at the "user_passes_test" function you'll see how to access request object.

A good tutorial about decorators : http://www.ibm.com/developerworks/linux/library/l-cpdecor.html For some examples of useful decorators see : http://wiki.python.org/moin/PythonDecoratorLibrary

Piotr Duda
+1  A: 

Thanks to Piotr for his helpful examples.

def fake_requested_from_root(fn):
    """
    Login decorator which when used on a view modifies the reqquest.path
    to fool the template into thibking that the request is coming from the
    root page
    """
    def decorator(request, **kwargs):
        request.path = reverse('home')
        return fn(request, **kwargs)
    return decorator
Mridang Agarwalla