1.发邮件配置
我使用的腾讯企业邮箱来发送邮件,首先需要登录邮箱确保权限的设置,如下图
image
image
在settings.py中添加邮箱配置
#配置邮箱发送者
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' #email后端
EMAIL_USE_TLS = False #是否使用TLS安全传输协议
EMAIL_USE_SSL = True #是否使用SSL加密,qq企业邮箱要求使用
EMAIL_HOST = 'smtp.exmail.qq.com' #发送邮件的邮箱 的 SMTP服务器,这里用了qq企业邮箱
EMAIL_PORT = 465 #发件箱的SMTP服务器端口
EMAIL_HOST_USER = 'liyong@7xiaofu.com' #发送邮件的邮箱地址
EMAIL_HOST_PASSWORD = 'XXXXXX' #发送邮件的邮箱密码
DEFAULT_FORM_EMAIL = 'liyong <liyong@7xiaofu.com>'
在apps路径下创建’utils‘python package文件夹,并创建email_send.py文件
需要引入系统的“from django.core.mail import send_mail”
代码如下
from random import Random
from django.core.mail import send_mail
from users.models import EmailVerifyRecord
from MxOnline.settings import EMAIL_HOST_USER
def random_str(randomlength=8):
str = ''
chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
length = len(chars) - 1
random = Random()
for i in range(randomlength):
str += chars[random.randint(0, length)]
return str
def send_email(email, send_type='register'):
email_record = EmailVerifyRecord()
if send_type == 'update_email':
code = random_str(4)
else:
code = random_str(16)
email_record.code = code
email_record.email = email
email_record.send_type = send_type
email_record.save()
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
elif send_type == 'forget':
email_title = '邮箱修改验证码'
email_body = '你的邮箱验证码为:{0}'.format(code)
send_status = send_mail(email_title, email_body, EMAIL_HOST_USER, [email])
if send_status:
pass
在views.py中的注册view类中添加发送邮件的使用
from utils.email_send import send_email
//example@example.com接收者邮箱
send_email(“example@example.com”, 'register')
2.验证码的使用
首先需要在虚拟环境中安装‘django-simple-captcha’和‘pillow’
pip install django-simple-captcha 用于验证码
pip install pillow 图像处理
然后在settings.py中的“INSTALLED_APPS”添加“ 'captcha', ”
分别执行一次“makemigrations”和“migration”
在RegisterForm中添加检测项
from captcha.fields import CaptchaField
class RegisterForm(forms.Form):
email = forms.EmailField(required=True)
password = forms.CharField(required=True, min_length=5)
captcha = CaptchaField(error_messages={'invalid' : '验证码错误'})
在html中使用的位置添加
<div>
<label>验 证 码</label>
{{ register_form.captcha }}
</div>
3.页面class
之前写页面是通过方法
# login in method
def user_login(request):
if request.method == 'POST':
username = request.POST.get('username','')
password = request.POST.get('password','')
user = authenticate(username=username, password=password)
if user is not None:
login(request,user)
return render(request, 'index.html')
else:
return render(request, 'login.html',{'msg':'用户名或者密码错误'})
elif request.method == 'GET':
return render(request,'login.html',{})
也可通过下面的方式
from django.views.generic.base import View
# login in class 登录
class LoginView(View):
def get(self,request):
return render(request, 'login.html',{})
def post(self,request):
login_form = LoginForm(request.POST)
if login_form.is_valid():
user_name = request.POST.get('username', '')
pass_word = request.POST.get('password', '')
user = authenticate(username=user_name, password=pass_word)
if user is not None:
if user.is_active:
login(request,user)
return render(request, 'index.html')
else:
return render(request, 'login.html', {'msg' : '用户未激活'})
else:
return render(request, 'login.html', {'msg' : '用户名或密码错误'})
else:
return render(request, 'login.html', {'login_form' : login_form})
LoginForm可以省去上面方法或者类中对于表单提交的参数的处理逻辑
from django import forms
class LoginForm(forms.Form):
username = forms.CharField(required=True) #required=True 表示不可为空
password = forms.CharField(required=True, min_length=5)
上面两种登录页面的方式在urls中的区别,分别为:
user_login:
from users.views import user_login
url(r'^login/$', user_login, name='login'),
LoginView:
from users.views import LoginView
from django.views.generic import TemplateView
url(r'^login/$', LoginView.as_view(), name='login'),
4.登录和注册
在项目的中的登录和注册中需要调用系统的登录和注册方法
导入“from django.contrib.auth import authenticate, login, logout”
user = authenticate(username=user_name, password=pass_word)//验证账号密码是否正确
if user is not None://表示账号密码正确然后调用系统的“login(request,user)”达到登录效果
退出的时候只需调用“logout(request)”即可
5.忘记密码-重置
重置密码的逻辑是首先输入邮箱提交申请,然后点击邮箱收到的链接,在链接中有标示用户的信息,查找得到用户的邮箱后将邮箱传递到输入密码的页面,然后将两次输入的密码和邮箱地址一块传递到重置密码的处理逻辑中
通过下面代码来传递邮箱
return render(request, 'password_reset.html', {'email' : email})
设置密码的页面
<li>
<span class="">新 密 码 :</span>
<input type="password" name="password" id="pwd" placeholder="6-20位非中文字符">
<i></i>
</li>
<li>
<span class="">确定密码:</span>
<input type="password" name="password2" id="repwd" placeholder="6-20位非中文字符">
<i></i>
</li>
<li>
<input type="hidden" name="email" value="{{ email }}">
</li>
网友评论