确认注册
......
css
跟ajax注册相关的js代码:
$("#registerbtn").click(function(){
$.ajax({
cache:false,
type:"POST",
url:"{%url'users:register'%}",
dataType:'json',
data:$('#registerform').serialize(),
//通过id找到提交form表单,并将表单转成字符串
async:true,
//异步为真,ajax提交的过程中,同时可以做其他的操作
success:function(data){
//jquery3以后,会将回传过来的字符串格式的data自动json解析不用再使用一遍JSON.parse(data)了,不然反而会在控制台报错
if(data.status){
$('#active-msg').html(data.status);
}else{
if(data.user){
username_msg=data.user.toString();
$('#user-msg').html('用户名'+username_msg);
}
if(data.email){
email_msg=data.email.toString();
$('#email-msg').html('邮箱'+email_msg);
}
if(data.pwd){
password_msg=data.pwd.toString();
$('#pwd-msg').html('密码'+password_msg);
}
if(data.captcha){
captcha_msg=data.captcha.toString();
$('#captcha-msg').html(captcha_msg);
}
msg=data.__all__.toString();
$('#active-msg').html(msg);
}
}
});
});
提升用户交互体验的js代码:
$("input").bind('inputpropertychange',function(){
$('#login-fail').html('');
$('#user-msg').html('');
$('#email-msg').html('');
$('#pwd-msg').html('');
$('#pwd-msg2').html('');
$('#captcha-msg').html('');
});
2.users/form.py代码:(要验证的字段名跟前端input框的name值要保持一致!)
fromdjangoimportforms
fromcaptcha.fieldsimportCaptchaField
from.modelsimportUserProfile
classRegisterForm(forms.Form):
"""注册信息的验证"""
user=forms.CharField(required=True,error_messages={'required':'用户名不能为空.'})
email=forms.EmailField(required=True,error_messages={'required':'邮箱不能为空.'})
pwd=forms.CharField(required=True,
min_length=6,
error_messages={'required':'密码不能为空.','min_length':"至少6位"})
pwd2=forms.CharField(required=True,
min_length=6,
error_messages={'required':'密码不能为空.','min_length':"至少6位"})
captcha=CaptchaField(error_messages={'invalid':'验证码错误'})
defclean(self):
'''验证两次密码是否一致'''
p1=self.cleaned_data.get('pwd')
p2=self.cleaned_data.get('pwd2')
ifp1!=p2:
raiseforms.ValidationError('两次输入密码不一致')
else:
returnself.cleaned_data
3.users/views.py中与注册相关的代码:
......
fromdjango.httpimportHttpResponse
from.modelsimportUserProfile,ShopProfile
fromusers.formimportRegisterForm
fromdjango.contrib.auth.hashersimportmake_password
importjson
classRegisterView(View):
"""邮箱注册"""
defpost(self,request):
register_form=RegisterForm(request.POST)
ifregister_form.is_valid():
user_name=request.POST.get('user','')
email=request.POST.get('email','')
pass_word=request.POST.get('pwd','')
u=UserProfile.objects.filter(username=user_name).count()
e=UserProfile.objects.filter(email=email).count()
ifuore:
returnHttpResponse('{"status":"该用户名或邮箱已被占用!"}')
else:
user_profile=UserProfile()
user_profile.username=user_name
user_profile.email=email
user_profile.password=make_password(pass_word)
user_profile.is_active=False
user_profile.save()
returnHttpResponse('{"status":"注册成功请去邮箱激活!"}')
msg=register_form.errors
msg=json.dumps(msg)
returnHttpResponse(msg)
4.配置users/urls.py注册路由:
......
from.viewsimportRegisterView
.....
urlpatterns=[
......
path('register/',RegisterView.as_view(),name='register'),
......
]
三、邮箱激活已注册的账号:
1.新建个数据表存放邮箱激活码:
在users/models.py中增加代码:
classEmailVerifyRecord(models.Model):
"""邮箱激活码"""
code=models.CharField(max_length=20,verbose_name='验证码')
email=models.EmailField(max_length=50,verbose_name='邮箱')
send_type=models.CharField(verbose_name='验证码类型',choices=(('register','注册'),('forget','忘记密码')),
max_length=20)
send_time=models.DateTimeField(verbose_name='发送时间',default=datetime.now)
classMeta:
verbose_name='邮箱验证码'
verbose_name_plural=verbose_name
def__str__(self):
return'{0}({1})'.format(self.code,self.email)
在users/adminx.py中注册数据表:
......
from.modelsimportEmailVerifyRecord
......
classEmailVerifyRecordAdmin(object):
list_display=['code','email','send_type','send_time']
search_fields=['code','email','send_type']
list_filter=['code','email','send_type','send_time']
......
xadmin.site.register(EmailVerifyRecord,EmailVerifyRecordAdmin)
打开终端Terminal执行更新数据库命令:
pythonmanage.pymakemigrations
pythonmanage.pymigrate
2.写发邮件的脚本:在apps/users/新建utils/email_send.py
fromrandomimportRandom
fromusers.modelsimportEmailVerifyRecord
fromdjango.core.mailimportsend_mail
fromxyw.settingsimportEMAIL_FROM
defrandom_str(randomlength=8):
str=''
chars='AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
length=len(chars)-1
random=Random()
foriinrange(randomlength):
str+=chars[random.randint(0,length)]
returnstr
defsend_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_title=''
email_body=''
ifsend_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])
ifsend_status:
pass
elifsend_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])
ifsend_status:
pass
3.在settings.py中追加发送邮件的配置代码:
EMAIL_HOST='smtp.sina.cn'
EMAIL_PORT=25
EMAIL_HOST_USER='xxxxxxxx@sina.cn'#你的邮箱
EMAIL_HOST_PASSWORD='********'
EMAIL_USE_TLS=False
EMAIL_FROM='xxxxxxx1@sina.cn'#同样是你的邮箱,跟上面都是发信者邮箱
#我用的新浪的,也可以用别的
4.开启新浪邮箱的smtp服务,不然不能自动发邮件的,步骤如下:
登录新浪邮箱====》设置区====》客户端pop/imp/smtp====》Pop3/SMTP服务====》服务状态:开启====》保存
5.增加激活功能
在users/views.py中增加激活类ActiveUserView(View)代码:
......
from.modelsimportEmailVerifyRecord
......
classActiveUserView(View):
"""激活账户"""
defget(self,request,active_code):
all_records=EmailVerifyRecord.objects.filter(code=active_code)
ifall_records:
forrecordinall_records:
email=record.email
user=UserProfile.objects.get(email=email)
user.is_active=True
user.save()
returnrender(request,'index.html')
6.在users/views.py中
对注册类RegisterView(View)增加发送激活邮件的代码:
......
fromapps.utils.email_sendimportsend_register_email
......
classRegisterView(View):
"""邮箱注册"""
defpost(self,request):
......
user_profile.save()
#发送邮件代码start
send_register_email(email,'register')
#发送邮件代码end
returnHttpResponse('{"status":"注册成功请去邮箱激活!"}')
对登录LoginView(View)增加验证账户激活与否的代码:
classLoginView(View):
"""用户登录"""
defpost(self,request):
user_name=request.POST.get("username","")
pass_word=request.POST.get("pwd","")
user=authenticate(username=user_name,password=pass_word)
ifuserisnotNone:
#验证账户是否已经激活start
ifuser.is_active:
login(request,user)
returnHttpResponse('{"status":"success"}')
else:
returnHttpResponse('{"status":"fail","msg":"账户未激活"}')
#验证账户是否已经激活end
else:
returnHttpResponse('{"status":"fail","msg":"用户名或密码错误"}')
至此完成了用邮箱注册及激活,很多时候,激活邮件都会被邮箱自动放入垃圾箱,而且从邮件点击激活链接的时候,还会被提示一些警告信息,可以说通过邮箱注册各种不如通过短信注册,但是……省钱啊!^_^
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。