简体   繁体   中英

Setting custom user object in context processor in django

I have a custom user model. After doing successful login, I am getting the anonymous user in HttpResponseRedirect and templates as well. How do I get the logged in user?

Login View:

class LoginFormView(View):
    form_class = UserLoginForm
    user_model = get_user_model()
    template_name = 'account/login.html'

    def get(self, request, *args, **kwargs):
        form = self.form_class
        return render(request, self.template_name, {'form':form})

    def post(self, request, *args, **kwargs):
        email = request.POST['email']
        password = request.POST['password']
        user = authenticate(email=email, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect(reverse('home'))
        else:
            messages.error(request, 'Please enter correct email and password!')
            return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))

If you have the request template context processor enabled, you'll be able to access the user in the template with {{ request.user}} .

Secondly, make sure you are importing the login function and not the login view . It should be:

from django.contrib.auth import login

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