Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Custom View Decorators

Alright I have a method called no_m in the user class and i've not written a decorator before, but basically I need to redirect the user to another URL if they pass this. I have created a file called decorators.py in a dir called accounts and i'm guessing the decorator is imported correctly, however I cannot get it to work. Heres what I have:

def no_m(view_func):
    def _wrapped_view_func(request, *args, **kwargs): 
        try:        
            if request.user.is_m():     
                # quick test
                return HttpResponseRedirect('http://google.com')            
            else:
                 return view_func(request, *args, **kwargs)     
        except:     
            return _wrapped_view_func

All it needs to do is redirect users if they pass that test, I don't know what the URL needs to be yet so it's just google for now. Any ideas? Like I said, i've not written decorators before so it's all new to me. Thankyou.

Another thought: would it be possible to render a template page?

like image 804
Callum Avatar asked Apr 22 '14 19:04

Callum


1 Answers

You're missing a step in the decorator, or rather you have a step confused. It's the outer function that must return the inner function (_wrapped_view_func), and it must always do so: that's what takes the place of the original function when it is called.

I'm not sure what the except clause is there for. Apart from it always being a bad idea to use a blank except - that catches everything, including things like ctrl-c - exceptions in Django functions are usually handled by the middleware, rather than the decorator. I would just remove it.

So the code should be:

def no_m(view_func):
    def _wrapped_view_func(request, *args, **kwargs): 
        if request.user.is_m():     
            # quick test
            return HttpResponseRedirect('http://google.com')            
        else:
             return view_func(request, *args, **kwargs)     
    return _wrapped_view_func
like image 72
Daniel Roseman Avatar answered Sep 30 '22 14:09

Daniel Roseman