简体   繁体   中英

How to check for user authentication in Django's class-based view with get_context_data

When using function based views in Django, I normally would check for user authentication with:

if not self.request.user.is_authenticated:
   return HttpResponseRedirect('/path/to/redirect')

Now I am trying to use Class based views instead but I don't know how to implement the authentication if I am using the get_context_data() method instead of just get() .

class MyGenericView(generic.ListView):
    model = models.MyModel
    template_name = 'path/to/template.html'
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['foo'] = 'bar'

        return context

You want to override the dispatch method.

class MyView(ListView):
    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            return HttpResponseRedirect('/path/to/redirect')

        return super().dispatch(request, *args, **kwargs)

More details in the doc .

You can use LoginRequiredMixin in the view to check if the user is authenitcated:

from django.contrib.auth.mixins import LoginRequiredMixin

class MyView(LoginRequiredMixin , ListView):
    login_url = “login_url_name”
    # rest of the code

You can also use user_passes_test , for example, in urls:

def user_authenticated(user):
    return user.is_authenticated


urlpatterns = [
    path(
       '',
        user_passes_test(user_authenticated, login_url='login')(
            MyView.as_view()
        ),
    )
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM