View of django class with decorator and sessions

I am trying to convert some of my django views from function based views to class based views, and I ran into a little problem.

My OO is a little weak, and I think the problem is that I lost information about where things are going.

I have a custom decoration decoder that I need on presentations, so I have ...

First I have a 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 cannot receive the request.session request 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 is simple that I will miss, thanks for your patience!

UPDATE: , , ...

"ViewDoesNotExist: TopSecretPage projectname.application.views. : type object 'TopSecretPage' 'session' '

, ....

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
+3
5

, "" , "" . , , , TopSecretPage.

Vinay, artran , . , .

+2

, , - django.utils.decorators.method_decorator(). , method_decorator(), / Django 1.2 . :

from django.utils.decorators import method_decorator

class TopSecretPage(View):
    @method_decorator(custom_login)
    def __call__(self, request, **kwargs):
        #bla bla view stuff...
        pass
+6

. , .

: :

class ContentView(View):

    # the thing in on_method() is the actual Django decorator
    #here are two examples
    @on_method(cache_page(60*5))
    @on_method(cache_control(max_age=60*5))
    def get(self, request, slug): # this is the decorated method
        pass #in here, you access request normally
+2

, , URL.

, urls.py:

from my_decorators import myuser_login_required
from my_views import TopSecretPage

urlpatterns = patterns('', 
    (r'^whatever-the-url-is/$', myuser_login_required(TopSecretPage), {}),
)

, , .

+1

Is this actually a duplicate of Django - The right way to pass arguments to CBV decorators?  which describes the correct way to solve this problem. The correct way to do this for django 1.9 is as follows:

@method_decorator(myuser_login_required(), name='dispatch')
class TopSecretPage(View):
    ..
0
source

Source: https://habr.com/ru/post/1717757/


All Articles