Django:实现重发激活链接视图并在登录页添加对应链接
没问题,我来帮你搞定这个Django重发激活链接的视图实现!下面是完整的分步方案,和你的模板完美适配:
实现Django重发激活链接视图
1. 先准备必要的导入模块
在你的views.py文件顶部导入这些依赖:
from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.contrib.auth.tokens import default_token_generator from django.core.mail import send_mail from django.template.loader import render_to_string from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.utils.encoding import force_bytes, force_str from django.contrib import messages from django import forms
2. 创建邮箱验证表单
先写一个简单的表单,用来接收用户邮箱并做基础校验:
class ResendActivationForm(forms.Form): email = forms.EmailField(label='Email', max_length=254) def clean_email(self): email = self.cleaned_data.get('email') # 校验邮箱对应的用户状态 try: user = User.objects.get(email=email) if user.is_active: raise forms.ValidationError("这个账号已经激活过啦!") except User.DoesNotExist: raise forms.ValidationError("没有找到对应这个邮箱的账号哦") return email
3. 实现核心视图(两种方式任选)
方式一:基于函数的视图(更直观)
def resend_activation(request): if request.method == 'POST': form = ResendActivationForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] user = User.objects.get(email=email) # 生成激活所需的UID和Token uid = urlsafe_base64_encode(force_bytes(user.pk)) token = default_token_generator.make_token(user) # 拼接完整的激活链接 activation_link = f"{request.scheme}://{request.get_host()}/activate/{uid}/{token}/" # 渲染邮件内容(可以用模板也可以直接写字符串) subject = '重新发送账号激活链接' message = render_to_string('activation_email.txt', { 'user': user, 'activation_link': activation_link, }) # 发送邮件 send_mail(subject, message, 'your-support-email@example.com', [email]) messages.success(request, '激活链接已经发送到你的邮箱啦,请查收!') return redirect('login') else: form = ResendActivationForm() return render(request, 'resend_activation.html', {'form': form})
方式二:基于类的视图(更符合Django规范)
如果你习惯用类视图,这个版本更简洁:
from django.views.generic import FormView class ResendActivationView(FormView): template_name = 'resend_activation.html' form_class = ResendActivationForm success_url = '/login/' def form_valid(self, form): email = form.cleaned_data['email'] user = User.objects.get(email=email) uid = urlsafe_base64_encode(force_bytes(user.pk)) token = default_token_generator.make_token(user) activation_link = f"{self.request.scheme}://{self.request.get_host()}/activate/{uid}/{token}/" subject = '重新发送账号激活链接' message = render_to_string('activation_email.txt', { 'user': user, 'activation_link': activation_link, }) send_mail(subject, message, 'your-support-email@example.com', [email]) messages.success(self.request, '激活链接已经发送到你的邮箱啦,请查收!') return super().form_valid(form)
4. 配置URL路由
在项目的urls.py里添加这条路由:
from django.urls import path from .views import resend_activation # 用类视图的话就导入ResendActivationView urlpatterns = [ # ... 其他已有的路由 path('resend-activation/', resend_activation, name='resend_activation'), # 类视图版本: # path('resend-activation/', ResendActivationView.as_view(), name='resend_activation'), ]
5. 可选:美化邮件内容
创建一个activation_email.txt模板(放在templates文件夹下),让邮件更友好:
嗨 {{ user.username }}, 我们收到了你重新发送激活链接的请求,点击下面的链接激活你的账号: {{ activation_link }} 如果你没有发起这个请求,忽略这封邮件就好啦。 谢谢, 你的团队
6. 在登录页面添加入口
最后在你的登录模板里加上指向这个功能的链接:
<p>没收到激活链接?<a href="{% url 'resend_activation' %}">点击重新发送</a></p>
重要提示
- 记得在
settings.py里配置好邮件服务(EMAIL_BACKEND、EMAIL_HOST等参数),不然邮件发不出去哦 - 如果用的是自定义用户模型,把代码里的
User替换成你的自定义模型类 - 要是你有自己的Token生成逻辑,替换掉
default_token_generator就行
内容的提问来源于stack exchange,提问作者Santhosh
相关产品推荐
相关产品推荐

