I want to restrict access to URLs handled by Django Generic Views.
For my Views I know that login_required
decorator does the job. Also Create/Delete/Update Generic Views take the login_required
argument, but I couldn't find a way to do this for other Generic Views.
Django's generic views were developed to ease that pain. They take certain common idioms and patterns found in view development and abstract them so that you can quickly write common views of data without having to write too much code.
from django.contrib.auth import authenticate, login def my_view(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) # Redirect to a success page. ... else: # Return an 'invalid ...
The intention of Generic Views is to reduce boilerplate code when you repeatedly use similar code in several views. You should really use it just for that. Basically, just because django allows something you are doing generically you shouldn't do it, particularly not when your code becomes not to your like.
Django 1.9 has introduced a LoginRequiredMixin
that is used thus:
from django.contrib.auth.mixins import LoginRequiredMixin class MyView(LoginRequiredMixin, View): login_url = '/login/' redirect_field_name = 'redirect_to'
If you are using an older version of django you can use pretty much the same mixin from django-braces - the Django version was based on the django-braces version. django-braces 1.4.x still supports Django 1.4 so you can use it with pretty old versions.
I found this question while googling for how to decorate class based views, so to add the answer for that:
This is covered in the documentation section on decorating class based views. There is the urls.py
wrapper, or you can apply the decorator to the dispatch()
method. Examples from the documentation:
from django.contrib.auth.decorators import login_required, permission_required from django.views.generic import TemplateView from .views import VoteView urlpatterns = patterns('', (r'^about/', login_required(TemplateView.as_view(template_name="secret.html"))), (r'^vote/', permission_required('polls.can_vote')(VoteView.as_view())), )
from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.views.generic import TemplateView class ProtectedView(TemplateView): template_name = 'secret.html' @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(ProtectedView, self).dispatch(*args, **kwargs)
See the documentation linked to above for more details.
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