如何为 django 自定义用户创建登录视图? [英] How to make a login view for django custom user?

查看:18
本文介绍了如何为 django 自定义用户创建登录视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 AbstractUser 创建了一个自定义用户模型,删除了用户名并用电子邮件替换它并扩展了模型,尝试创建超级用户并且它工作并且还通过注册表创建了一些用户,登录到管理界面并且它然而,当试图为用户创建登录表单时它失败了

I have made a custom user model using the AbstractUser , removed the username and replaced it with email and extended the model, tried creating superuser and it worked and also created some users by a signup form , logged in the admin interface and it worked however when tried to create a login form for the users it fails

我试过了,但没有用

def LoginView(request):
    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            user = form.get_user()
            login(request,user)
            return redirect('accounts:login')
    else:
        form = AuthenticationForm()
    return render(request,'accounts/login.html', {'form':form})

然后我尝试了这个

class LoginView(FormView):
   form_class = AuthenticationForm
   template_name = 'login.html'

   def form_valid(self, form):
       email = form.cleaned_data['email']
       password = form.cleaned_data['password']
       user = authenticate(email=email, password=password)

    # Check here if the user is an admin
       if user is not None and user.is_active:
           login(self.request, user)
           return HttpResponseRedirect(self.success_url)
       else:
           return self.form_invalid(form)

显然我希望用户登录我认为这篇文章中的代码格式不正确.主要是我的错,因为我是这个平台的新手

Obviously i expect the user to be logged in i think the code in this post is badly formatted. mainly it's my fault as i'm new to this platform

推荐答案

我开发了与您描述的几乎相同的设置(我没有删除用户名字段,只是停止使用它).如果你还没有看过它,Django 的文档位于 https://docs.djangoproject.com/en/2.2/topics/auth/customizing/#substituting-a-custom-user-model 很有帮助.

I've developed almost the same setup that you're describing (I didn't remove the username field, just stopped using it). If you haven't already seen it, Django's documentation at https://docs.djangoproject.com/en/2.2/topics/auth/customizing/#substituting-a-custom-user-model is quite helpful.

有一些重要的事情需要正确设置才能正常工作.

There are a couple of important things that need to be set up correctly for this to work.

  • 模型上的 USERNAME_FIELD 应设置为电子邮件字段的名称.
  • AUTH_USER_MODEL 需要指向您的自定义用户模型.
  • The USERNAME_FIELD on your model should be set to the name of your email field.
  • The AUTH_USER_MODEL needs to point to your custom user model.
class MyUser(AbstractUser):
    USERNAME_FIELD = 'email'

AUTH_USER_MODEL = 'customauth.MyUser'

由于您完全删除了用户名字段,您可能需要子类化 django.contrib.auth.forms.AuthenticationFormdjango.contrib.auth.views.LoginView以避免破坏事情,但 Django 应该很好地处理不同的身份验证字段.

Since you've removed the username field altogether you might need to subclass django.contrib.auth.forms.AuthenticationForm and django.contrib.auth.views.LoginView to avoid breaking things, but Django should handle a different authentication field quite well.

如果您确实需要对视图进行子类化,https://ccbv.co.uk/projects/Django/2.2/django.contrib.auth.views/LoginView/ 是查看所有方法的好地方看看发生了什么.

If you do wind up needing to subclass the view, https://ccbv.co.uk/projects/Django/2.2/django.contrib.auth.views/LoginView/ is a great place to look over all the methods to see what's going on.

编辑 - 关于子类化及其必要性

我所说的可能需要对某些事物进行子类化的内容受到 https://docs.djangoproject.com/en/2.2/topics/auth/customizing/#writing-a-manager-for-a-custom-user-模型.我不确定身份验证系统的其他部分是否需要您自定义它们,因为您删除了用户名字段.

What I was saying about possibly needing to subclass certain things was influenced by https://docs.djangoproject.com/en/2.2/topics/auth/customizing/#writing-a-manager-for-a-custom-user-model. I wasn't sure if there were other parts of the authentication system that would need you to customize them because you removed the username field.

我已经阅读了一些 Django 认证系统的源代码.这是正在遵循的路径.

I've read through some of the source code for Django's authentication system. Here's the path that's being followed.

  1. 当 POST 请求被发送到 Django 的认证视图时,认证表单被验证.https://github.com/django/django/blob/2.2.2/django/contrib/auth/forms.py#L191

身份验证函数被调用.这会遍历设置的后端并尝试对每个后端进行身份验证.https://github.com/django/django/blob/2.2.2/django/contrib/auth/__init__.py#L62

The authenticate function is called. This iterates through the backends set up and tries to authenticate on each of them. https://github.com/django/django/blob/2.2.2/django/contrib/auth/__init__.py#L62

Django 的内置身份验证后端使用自然密钥获取用户(如果存在).https://github.com/django/django/blob/2.2.2/django/contrib/auth/backends.py#L16

Django's built-in authentication backend gets the user if it exists using the natural key. https://github.com/django/django/blob/2.2.2/django/contrib/auth/backends.py#L16

我们可以在基本管理器中看到,使用的自然键是由 USERNAME_FIELD 命名的字段.https://github.com/django/django/blob/2.2.2/django/contrib/auth/base_user.py#L43

We can see in the base manager that the natural key used is the field named by USERNAME_FIELD. https://github.com/django/django/blob/2.2.2/django/contrib/auth/base_user.py#L43

如果表单有效,意味着用户通过了正确的身份验证,则用户登录.https://github.com/django/django/blob/2.2.2/django/contrib/auth/views.py#L88

If the form is valid, meaning that the user is authenticated properly, the user is then logged in. https://github.com/django/django/blob/2.2.2/django/contrib/auth/views.py#L88

我的反应是,看起来 Django 应该为您的用例开箱即用.您不应该需要编写后端.这是我的直觉告诉你应该编写的代码的范围.

My reaction is that it looks like Django should work out of the box for your use case. You shouldn't need to write a backend. Here's the extent of the code my gut says you should have to write.

from django.contrib.auth import views as auth_views
from django.shortcuts import resolve_url

class LoginView(auth_views.LoginView):
    template_name = 'accounts/login.html'

    def get_success_url(self):
        return resolve_url('accounts:login')

这篇关于如何为 django 自定义用户创建登录视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆