[英]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.
成功登录后,我将在HttpResponseRedirect和模板中获取匿名用户。 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}}
. 如果您启用了请求模板上下文处理器 ,则可以使用
{{ 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.