django allauth 自定义登录界面

发布于:2025-03-12 ⋅ 阅读:(19) ⋅ 点赞:(0)

起因, 目的:

  1. 为什么前几天还在写强化学习,今天又写 django, 问就是:客户需求 > 个人兴趣。
  2. 问题来源:allauth 默认的登录界面不好看,这里记录几个问题。

1. 注册页面 SignUp

这里增加, 手机号,邮编等等。
在这里插入图片描述

2. 使用谷歌来登录

这个步骤其实也简单。
请添加图片描述
xxxxxxxx 一定要修改关键的信息,不能随便暴露给别人。xxxxxxxx

# How to use Google Login. 
1. create superuser. (my admin account is: name = admin, password = adminpass)
2. login to admin page. (http://127.0.0.1:8000/admin)
3. Find "social application" and "ADD social application"
4. Fill the values, :
    - Provider: Google
    - Name: Google Login
    - Client id: 1044xxxxxxxxxxxxxxxxxxxxxxxd.apps.googleusercontent.com
    - Client secret :GOCxxxxxxxxxxxxMJJqNpmEE0d
    - Save !
5. Now, test Google Login.
3. 如何修改默认的登录页面 login view

默认的登录方式是,用户名+密码,而我想使用 邮箱+密码。

  1. 在 settings.py, 增加下面这些,一定要注意拼写错误。
    AUTHENTICATION_BACKENDS = [
        "django.contrib.auth.backends.ModelBackend",
        "allauth.account.auth_backends.AuthenticationBackend"
    ]
    
    EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
    ACCOUNT_LOGIN_METHODS = {'email'}
    
    ACCOUNT_EMAIL_REQUIRED = True
    ACCOUNT_USERNAME_REQUIRED = False
    ACCOUNT_UNIQUE_EMAIL = True
    
  2. 自定义登录表单, 这部分,我反复查看了很久,阅读源码等等:
     class CustomLoginForm(LoginForm):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.fields['login'].label = 'Email' # !!!!!!!!!!!!
            self.fields['login'].widget.attrs.update({'placeholder': 'Email'})
            self.fields['password'].widget.attrs.update({'placeholder': 'Password'})
    
        def clean_email(self):
            email = self.cleaned_data.get('email')
            return email
    
        def clean_password(self):
            password = self.cleaned_data.get('password')
            return password
    

结论 + todo

这次就先这样,简单记录一下过程。完整代码,估计下次。