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?
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.
Allowed HTTP methodsviews. decorators. http can be used to restrict access to views based on the request method.
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.
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.
In your urls
url(r'someregexp/$', mydecorator(view.myview.dude), 'name_of_view'),
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With