Django项目 | 实现登录注册验证电子邮箱

在实现登录验证电子邮箱时,需要确保模型中包含电子邮箱字段

自定义用户模型登录验证电子邮箱实现

1. 模型(Model)

确保自定义用户模型中包含电子邮箱字段。例如:

python 复制代码
from django.contrib.auth.models import AbstractUser
from django.db import models

class CustomUser(AbstractUser):
    email = models.EmailField(unique=True)
    # 其他自定义字段...

2. 表单(Form)

创建或修改用户登录表单,以包含电子邮箱字段。

python 复制代码
from django import forms
from django.contrib.auth import get_user_model

User = get_user_model()

class EmailAuthenticationForm(forms.Form):
    email = forms.EmailField(label="Email", max_length=254, widget=forms.EmailInput(attrs={'autofocus': True}))
    password = forms.CharField(label="Password", widget=forms.PasswordInput)

    def clean(self):
        cleaned_data = super().clean()
        email = cleaned_data.get('email')
        password = cleaned_data.get('password')

        if email and password:
            if not User.objects.filter(email=email).exists():
                raise forms.ValidationError("Email is not registered")
            user = authenticate(username=email, password=password)
            if not user:
                raise forms.ValidationError("Invalid email or password")

3. 视图(View)

在登录视图中添加逻辑来验证电子邮箱。

python 复制代码
from django.contrib.auth import authenticate, login
from django.shortcuts import render, redirect
from .forms import EmailAuthenticationForm

def user_login(request):
    if request.method == 'POST':
        form = EmailAuthenticationForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data.get('email')
            password = form.cleaned_data.get('password')
            user = authenticate(request, email=email, password=password)
            if user is not None:
                login(request, user)
                return redirect('home')
            else:
                form.add_error(None, "Invalid email or password.")
    else:
        form = EmailAuthenticationForm()
    return render(request, 'users/login.html', {'form': form})

4. 模板(Template)

在登录页面模板中添加电子邮箱输入字段。

html 复制代码
<!-- users/login.html -->
<form method="post">
    {% csrf_token %}
    {{ form.email.errors }}
    <label for="email">Email:</label>
    <input type="email" name="email" required id="email">
    {{ form.password.errors }}
    <label for="password">Password:</label>
    <input type="password" name="password" required id="password">
    <button type="submit">Login</button>
</form>

5. 信号(Signal)

使用Django的信号在用户注册后发送验证邮件。

python 复制代码
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.core.mail import send_mail
from django.conf import settings

@receiver(post_save, sender=User)
def send_verification_email(sender, instance, created, **kwargs):
    if created:
        subject = 'Verify your email'
        message = f'Hello {instance.email}, Please click on the link to verify your email.'
        link = f'http://{settings.SITE_DOMAIN}verify/{instance.id}/{instance.email_token}/'
        send_mail(subject, message + link, settings.EMAIL_HOST_USER, [instance.email], fail_silently=False)

6. URLs

配置URL以处理验证链接的请求。

python 复制代码
# urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('login/', views.user_login, name='login'),
    path('verify/<int:user_id>/<str:token>/', views.verify_email, name='verify_email'),
]

确保您的项目配置了邮件发送相关的设置,如EMAIL_BACKEND, EMAIL_HOST, EMAIL_PORT, EMAIL_HOST_USER, EMAIL_HOST_PASSWORD等。在项目的settings.py文件中添加或修改以下配置项。以下是具体的配置示例:

python 复制代码
# settings.py

# 邮件后端设置
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

# SMTP 服务器设置
EMAIL_HOST = 'smtp.yourmailserver.com'  # SMTP 服务器地址
EMAIL_PORT = 587  # SMTP 服务器端口(通常是587或465)
EMAIL_USE_TLS = True  # 是否使用TLS(对于大多数SMTP服务器是必需的)
# 或者使用SSL
# EMAIL_USE_SSL = True
# EMAIL_PORT = 465  # 如果使用SSL,端口通常是465

# 发件人设置
EMAIL_HOST_USER = 'your-email@example.com'  # 发件人邮箱地址
EMAIL_HOST_PASSWORD = 'your-email-password'  # 发件人邮箱密码或应用专用密码

# 可选设置
EMAIL_SUBJECT_PREFIX = '[YourProject] '  # 发送邮件的主题前缀
EMAIL_FROM_ADDRESS = 'webmaster@yourdomain.com'  # 默认发件人地址
EMAIL_TIMEOUT = 10  # 发送邮件的超时时间(秒)

请根据您的邮件服务提供商和个人账户信息,替换上述配置中的占位符(如yourmailserver.com、your-email@example.com和your-email-password)。

常见邮件服务提供商的SMTP设置:

  • Gmail:

    • EMAIL_HOST = 'smtp.gmail.com'
    • EMAIL_PORT = 587(使用TLS)
    • EMAIL_USE_TLS = True
    • EMAIL_HOST_USER = 'your-email@gmail.com'
    • EMAIL_HOST_PASSWORD = 'your-gmail-password'(或者使用应用专用密码)
  • Outlook.com:

    • EMAIL_HOST = 'smtp-mail.outlook.com'
    • EMAIL_PORT = 587(使用TLS)
    • EMAIL_USE_TLS = True
    • EMAIL_HOST_USER = 'your-email@outlook.com'
    • EMAIL_HOST_PASSWORD = 'your-outlook-password'
  • Yahoo Mail:

    • EMAIL_HOST = 'smtp.mail.yahoo.com'
    • EMAIL_PORT = 465(使用SSL)
    • EMAIL_USE_SSL = True
    • EMAIL_HOST_USER = 'your-email@yahoo.com'
    • EMAIL_HOST_PASSWORD = 'your-yahoo-password'

确保您的邮箱账户允许通过SMTP发送邮件,并且您已经正确设置了应用专用密码(如果使用两步验证的话)。这些设置将使您的Django项目能够发送邮件,例如在用户注册时发送验证邮件。

相关推荐
子兮曰4 天前
jev-ultrafast 深度解析:7 秒订机票的浏览器 Agent 是如何炼成的
前端·后端·agent
子兮曰4 天前
Jev 爆发一周:7 秒 Agent 背后的 System One 生态与三场争议
前端·后端·ai编程
爱勇宝4 天前
ZCode 开源 24 小时:一份没有历史的账本,回答不了"有没有偷代码"
前端·后端·chatglm (智谱)
胡写代码4 天前
别再前后端各写一套表单校验了
java·后端
小白男神4 天前
MySQL进阶学习四(存储过程、游标、触发器)
mysql
大勇前进4 天前
原生 PHP 还是 Laravel?小项目到底要不要上框架
后端
这个DBA有点耶4 天前
MVCC深入:Read View、版本链与快照读——InnoDB并发控制的内核
数据库·mysql·架构
yuzhi_liu4 天前
我用 LangGraph4j 实现 Multi-Agent Supervisor
后端
alsmile4 天前
Node-RED 之外,国产规则引擎的新方案:基于标准语法,Go 先行实现
后端·开源·go
大白804 天前
PHP 内存溢出排查思路:看懂报错日志,精准定位问题
后端