I'm trying to convert some of my django views over from function based views to class based views and I've run into a small problem.
My OO is kind of weak and I think the problem is that I've lost track of where things are going.
I have a custom login decorator that I need on the views so I have...
First I have the View class from this example http://www.djangosnippets.org/snippets/760/
Then my view class looks like this...
class TopSecretPage(View):
@custom_login
def __call__(self, request, **kwargs):
#bla bla view stuff...
pass
The problem is that my decorator can't access request.session for some reason...
My decorator looks like this...
def myuser_login_required(f):
def wrap(request, *args, **kwargs):
# this check the session if userid key exist,
# if not it will redirect to login page
if 'field' not in request.session.keys():
return wrap
I think it's something simple that I'm missing so thanks for your patience everyone!
UPDATE: Ok so here's the error that I get...
"ViewDoesNotExist: Tried TopSecretPage in module projectname.application.views. Error was: type object 'TopSecretPage' has no attribute 'session'"
I simplified the decorator as well to look like this....
def myuser_login_required(request, *args, **kwargs):
# this check the session if userid key exist,
# if not it will redirect to login page
if 'username' not in request.session.keys():
return HttpResponseRedirect(reverse("login-page"))
return True
The correct way to do this for any decorator applied to any class-based view method is to use
django.utils.decorators.method_decorator()
. I'm not sure when method_decorator() was introduced but here is an example/update in the Django 1.2 release notes. Use it like this:This is effectively a duplicate of Django - Correct way to pass arguments to CBV decorators? which describes the correct way of addressing this. The correct way of doing this for django 1.9 is as follows:
The problem is that your wrapper expects "request" as the first argument, but a method on a class always takes "self" as the first argument. So in your decorator, what it thinks is the request object is actually TopSecretPage itself.
Either Vinay or artran's solutions should work, so I won't repeat them. Just thought a clearer description of the problem might be helpful.
Instead of using the decorator on the view you could decorate the url.
For example in urls.py:
You may need to play with that a little but it's about right.
This problem has come up before. A solution is included which might work for you.
Update: Example method with decorator: