urls.py
from django.urls import path, re_path, include
from django.contrib.auth.views import PasswordResetDoneView
from django.contrib.auth.views import LoginView
from django.contrib.auth.views import LogoutView
from django.contrib.auth.views import logout_then_login
from django.contrib.auth.views import PasswordResetConfirmView
from django.contrib.auth.views import PasswordResetCompleteView
from django.contrib.auth.views import PasswordResetView
from user import views
path('login/', LoginView.as_view(), name='login'),
path('logout/', LogoutView.as_view(), name='logout'),
path('logout_then_login/', logout_then_login, name='logout_then_login'),
#在as_view中制定自定义的邮箱认证表单类
path('password-reset/', PasswordResetView.as_view(form_class=views.CustomPasswordChangeForm), name='password_reset'),
re_path(r'^password-reset/confirm/(?P<uidb64>[-w]+)/(?P<token>[-w]+)/$', PasswordResetConfirmView.as_view(),
name='password_reset_confirm'),
path('password-reset/complete/', PasswordResetCompleteView.as_view(), name='password_reset_complete'),
path('password-reset/done/', PasswordResetDoneView.as_view(), name='password_reset_done'),
user.views.py
from django.contrib.auth.views import PasswordResetForm
from django.contrib.auth.models import User
from django.forms import ValidationError
#如果用户注册的时候没有填写邮箱,django只会不发送邮件不会报错,所以需要自定义Form添加邮箱验证如果邮箱不存在添加错误
class CustomPasswordChangeForm(PasswordResetForm):
def clean_email(self):
email = self.cleaned_data['email']
if User.objects.filter(email=email):
return email
else:
self.add_error('email',ValidationError('邮箱未注册'))
registration/password_reset_email.html
django默认的发送邮件格式
Someone asked for password reset for email {{ email }}. Follow the link below:
{{ protocol }}://{{ domain }}{% url "password_reset_confirm" uidb64=uid token=token %}
Your username, in case you've forgotten: {{ user.get_username }}
setting.py
设置邮箱配置
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_SSL = True
EMAIL_HOST = 'smtp.qq.com'
EMAIL_HOST_USER = '541260561@qq.com'
EMAIL_HOST_PASSWORD = 'lgtbakuvoyfsbbjd'#qq邮箱开启SMTP服务后随机生成的密码
EMAIL_PORT = 465
EMAIL_FROM = '生鲜<541260561@qq.com>'
DEFAULT_FROM_EMAIL = EMAIL_FROM
from django.urls impost reverse_lazy #惰性反向匹配url在app没有加载完全的时候也可以匹配成功
LOGIN_REDIRECT_URL = reverse_lazy('account:dashboard')
LOGIN_URL = reverse_lazy('login')
LOGOUT_URL = reverse_lazy('logout')