django關於實現找回密碼功能-----通過郵件來重置密碼
阿新 • • 發佈:2018-12-11
- 首先要呼叫傳送郵件的函式,要成功的傳送跳轉地址,這裡的跳轉地址要儲存在資料庫中,以便以後可以知道是哪個賬號要進行重置密碼
# _*_ coding: utf-8 _*_
__author__ = 'LelandYan'
__date__ = '2018/9/17 13:38'
from random import Random
from django.core.mail import send_mail
from users.models import EmailVerifyRecord
from MxOnline.settings import EMAIL_FROM
def send_register_email (email, send_type="register"):
email_record = EmailVerifyRecord()
code = random_str(16)
email_record.code = code
email_record.email = email
email_record.send_type = send_type
email_record.save()
#上面是將驗證碼和email儲存在資料庫中
email_title = ""
email_body = ""
if send_type == "register":
email_title = "慕學線上網註冊啟用連結"
email_body = "請點選下面的連結啟用你的賬號: http://127.0.0.1:8000/active/{0}".format(code)
send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])
if send_status:
pass
elif send_type == 'forget':
email_title = "慕學線上網密碼重置連結"
email_body = "請點選下面的連結啟用你的賬號: http://127.0.0.1:8000/reset/{0}".format(code)
send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])
if send_status:
pass
#隨機生成驗證碼
def random_str(randomlength=8):
str = ''
chars = 'abcdefghijklmnopqrstuvwsyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
length = len(chars) - 1
random = Random()
for i in range(randomlength):
str += chars[random.randint(0, length)]
return str
- views.py中書寫倆個檢視類其中一個為對傳送的郵件的網址的解析
其中html中還應該有form表單,然後是form表單跳轉的頁面,要判斷密碼是否修改成功
這裡注意一個為get一個為post
class RestView(View):
def get(self, request, active_code):
all_records = EmailVerifyRecord.objects.filter(code=active_code)
if all_records:
for record in all_records:
email = record.email
return render(request, 'password_reset.html', {"email": email})
else:
return render(request, 'active_fail.html', {})
return render(request, 'login.html', {})
class ModifyView(View):
def post(self, request):
modify_form = ModifyPwdForm(request.POST)
if modify_form.is_valid():
pwd1 = request.POST.get('password1', '')
pwd2 = request.POST.get('password2', '')
email = request.POST.get('email', '')
if pwd1 != pwd2:
return render(request, 'password_reset.html', {'msg': '密碼不一致', 'email': email})
user = UserProfile.objects.get(email=email)
user.password = make_password(pwd2)
user.save()
return render(request, 'login.html', {})
else:
email = request.POST.get('email', '')
return render(request, 'password_reset.html', {'modify_form': modify_form, 'email': email})
def get(self, request):
return render(request, 'index.html')
- 還要對url進行配置
url(r'^reset/(?P<active_code>.*)/$', RestView.as_view(), name='reset_pwd'),
url(r'^modify/$', ModifyView.as_view(), name='modify_pwd'),
- 這裡注意這裡檢視類必須要兩個,不可以合起來,因為第一個url在html中要攜帶引數,所以定義了倆個試圖類