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

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

1. 模型(Model)

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

from django.contrib.auth.models import AbstractUser
from django.db import models

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

2. 表单(Form)

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

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)

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

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)

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

<!-- 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的信号在用户注册后发送验证邮件。

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以处理验证链接的请求。

# 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文件中添加或修改以下配置项。以下是具体的配置示例:

# 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.comyour-email@example.comyour-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项目能够发送邮件,例如在用户注册时发送验证邮件。

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部