Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply a decorator to all views (of a module) in django

It happens a lot, when all the views in a specific module are supposed to be available only when the user is authorized, or they should all do the same checks.

How could I avoid repeating the annotations all over the file?

like image 664
semekh Avatar asked May 21 '13 07:05

semekh


People also ask

How do you use decorators in class based views django?

You need to apply the decorator to the dispatch method of the class based view. This can be done as follows: class ProfileView(View): @youdecorator def dispatch(self,request,*args,**kwargs): return super(ProfileView,self). dispatch(request,*args,**kwargs) //Rest of your code.

Which view decorator module can be used to restrict access to views based on the request method?

Allowed HTTP methodsviews. decorators. http can be used to restrict access to views based on the request method.

How do you use decorators in django?

To add a decorator function to every instance of a class-based view, you need to decorate the class definition itself. To do this, you pass the name of the method to be decorated as the keyword argument name: from . decorators import authentication_not_required from django.

How do you call class based views in django?

import asyncio from django. http import HttpResponse from django. views import View class AsyncView(View): async def get(self, request, *args, **kwargs): # Perform io-blocking view logic using await, sleep for example. await asyncio.


2 Answers

In your urls

url(r'someregexp/$', mydecorator(view.myview.dude), 'name_of_view'),
like image 108
Henrik Andersson Avatar answered Sep 19 '22 13:09

Henrik Andersson


When using class-based views you can create a base class/mixin for all these views which implements the desired functionality (also using decorators) and then have all the views inherit from this base view.

from django.views.generic import TemplateView

class BaseView(TemplateView):

    def get(self, request, *args, **kwargs):
        # do some checking here
        if not request.user.is_authenticated():
            # do something if anonymous user
        return super(BaseView, self).get(request, *args, **kwargs)


class MyView(BaseView):
    pass
like image 40
Bernhard Vallant Avatar answered Sep 17 '22 13:09

Bernhard Vallant