我有自定义用户模型。成功登录后,我将获得HttpResponseRedirect和模板中的匿名用户。如何获取登录用户?
登录视图:
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', '/'))
答案 0 :(得分:1)
如果您启用了request template context processor,则可以使用{{ request.user}}
访问模板中的用户。
其次,请确保您要导入登录功能,而不是登录视图。它应该是:
from django.contrib.auth import login