马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
在实现登录验证电子邮箱时,需要确保模型中包含电子邮箱字段
自定义用户模型登录验证电子邮箱实现
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.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项目能够发送邮件,比方在用户注册时发送验证邮件。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |