django 通過(guò)ajax完成郵箱用戶(hù)注冊(cè)、激活賬號(hào)的方法
一、圖片驗(yàn)證碼
django-simple-captcha配置
1.在pycharm中,F(xiàn)ile====》Settings====》Project:項(xiàng)目名====》Project Interpreter====》+====》搜django-simple-captcha 選擇0.55以上版本,然后點(diǎn)install package 按鈕進(jìn)行安裝
2.項(xiàng)目名/urls.py中添加代碼:
from django.urls import path,include
......
from users.views import IndexView
......
urlpatterns = [
......
#配置驗(yàn)證碼
path('captcha/',include('captcha.urls')),
#首頁(yè)url
path('', IndexView.as_view(), name='index'),
......
]
3.settings.py中添加一個(gè)注冊(cè)信息
INSTALLED_APPS = [
......
'captcha'
]
4.打開(kāi)終端Terminal執(zhí)行更新數(shù)據(jù)庫(kù)命令:
python manage.py makemigrations python manage.py migrate
5.在users目錄下新建form.py文件:
from django import forms
from captcha.fields import CaptchaField
......
class RegisterForm(forms.Form):
"""注冊(cè)信息的驗(yàn)證"""
......
captcha=CaptchaField(error_messages={'invalid':'驗(yàn)證碼錯(cuò)誤'})
......
6.在users/views.py中添加代碼:
from users.form import RegisterForm
class IndexView(View):
"""首頁(yè)"""
def get(self,request):
register_form=RegisterForm()
return render(request,'index.html',{'register_form':register_form})
7.在前端首頁(yè)index.html中顯示驗(yàn)證碼、輸入框
html
<div class="modal fade" id="register" tabindex="-1" role="dialog">
......
<!--模態(tài)框中關(guān)于注冊(cè)的內(nèi)容start-->
<div class="modal-body">
......
<P><div style="display: inline-block;width:100px;text-align: center"><b >驗(yàn)證碼:</b></div>
<!--驗(yàn)證碼start-->
<div class="cap">{{ register_form.captcha }}</div>
<!--驗(yàn)證碼end-->
</P>
{% csrf_token %}
</form>
<p><div style="margin-left: 100px;background-color: orangered;width:150px;text-align: center"><b></b></div></p>
</div>
<!--模態(tài)框中關(guān)于注冊(cè)的內(nèi)容end-->
......
css
<style>
.cap{
display: inline-block;
width: 280px;
height: 36px;
}
.cap img{
float: right;
}
</style>
js 跟刷新驗(yàn)證碼相關(guān)(需要先引入jQuery)
$(function(){
$('.captcha').css({
'cursor': 'pointer'
});
/*# ajax 刷新*/
$('.captcha').click(function(){
console.log('click');
$.getJSON("/captcha/refresh/",function(result){
$('.captcha').attr('src', result['image_url']);
$('#id_captcha_0').val(result['key'])
});
});
})
二、ajax郵箱注冊(cè)
1.在前端跟注冊(cè)綁定的模態(tài)框代碼寫(xiě)成:
html
<div class="modal fade" id="register" tabindex="-1" role="dialog">
......
<div class="modal-body">
<form id="registerform" action="#" method="post">
<p>
<div class="re-input"><b>用戶(hù)名:</b></div>
<input type="text" name="user" placeholder="用戶(hù)名">
<div class="msg"><b id="user-msg"></b></div>
</p>
<p>
<div class="re-input"><b>郵箱:</b></div>
<input type="text" name="email" placeholder="郵箱">
<div class="msg"><b id="email-msg">2222</b></div>
</p>
<p>
<div class="re-input"><b >密碼:</b></div>
<input type="password" name="pwd" placeholder="密碼(不少于6位)">
<div class="msg"><b id="pwd-msg">222</b></div>
</p>
<p>
<div class="re-input"><b >確認(rèn)密碼:</b></div>
<input type="password" name="pwd2" placeholder="確認(rèn)密碼">
<div class="msg"><b id="pwd-msg2">22</b></div>
</p>
<P><div class="re-input"><b >驗(yàn)證碼:</b></div>
<div class="cap">{{ register_form.captcha }}</div>
<div class="msg"><b id="captcha-msg">2</b></div>
</P>
{% csrf_token %}
</form>
<p><div style="margin-left: 100px;color: white;background-color: green;width:180px;text-align: center"><b id="active-msg"></b></div></p>
......
<button type="button" class="btn btn-primary" id="registerbtn">確認(rèn)注冊(cè)</button>
......
css
<style>
.cap{
display: inline-block;
width: 280px;
height: 36px;
}
.cap img{
float: right;
}
.re-input{
display: inline-block;
width:100px;
text-align: center
}
.msg{
margin-left: 100px;
background-color: orangered;
width:180px;
text-align: center
}
</style>
跟ajax注冊(cè)相關(guān)的js代碼:
$("#registerbtn").click(function() {
$.ajax({
cache:false,
type:"POST",
url:"{% url 'users:register' %}",
dataType:'json',
data:$('#registerform').serialize(),
//通過(guò)id找到提交form表單,并將表單轉(zhuǎn)成字符串
async:true,
//異步為真,ajax提交的過(guò)程中,同時(shí)可以做其他的操作
success:function (data) {
//jquery3以后,會(huì)將回傳過(guò)來(lái)的字符串格式的data自動(dòng)json解析不用再使用一遍JSON.parse(data)了,不然反而會(huì)在控制臺(tái)報(bào)錯(cuò)
if(data.status){
$('#active-msg').html(data.status);
} else{
if(data.user){
username_msg=data.user.toString();
$('#user-msg').html('用戶(hù)名'+ 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);
}
}
});
});
提升用戶(hù)交互體驗(yàn)的js代碼:
$("input").bind('input propertychange', function() {
$('#login-fail').html('');
$('#user-msg').html('');
$('#email-msg').html('');
$('#pwd-msg').html('');
$('#pwd-msg2').html('');
$('#captcha-msg').html('');
});
2.users/form.py代碼:(要驗(yàn)證的字段名跟前端input框的name值要保持一致?。?/p>
from django import forms
from captcha.fields import CaptchaField
from .models import UserProfile
class RegisterForm(forms.Form):
"""注冊(cè)信息的驗(yàn)證"""
user = forms.CharField(required=True, error_messages={'required': '用戶(hù)名不能為空.'})
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':'驗(yàn)證碼錯(cuò)誤'})
def clean(self):
'''驗(yàn)證兩次密碼是否一致'''
p1=self.cleaned_data.get('pwd')
p2=self.cleaned_data.get('pwd2')
if p1!=p2:
raise forms.ValidationError('兩次輸入密碼不一致')
else:
return self.cleaned_data
3.users/views.py中與注冊(cè)相關(guān)的代碼:
......
from django.http import HttpResponse
from .models import UserProfile,ShopProfile
from users.form import RegisterForm
from django.contrib.auth.hashers import make_password
import json
class RegisterView(View):
"""郵箱注冊(cè)"""
def post(self, request):
register_form=RegisterForm(request.POST)
if register_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()
if u or e:
return HttpResponse('{"status":"該用戶(hù)名或郵箱已被占用!"}')
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()
return HttpResponse('{"status":"注冊(cè)成功請(qǐng)去郵箱激活!"}')
msg=register_form.errors
msg=json.dumps(msg)
return HttpResponse(msg)
4.配置users/urls.py注冊(cè)路由:
......
from .views import RegisterView
.....
urlpatterns = [
......
path('register/',RegisterView.as_view(),name='register'),
......
]
三、郵箱激活已注冊(cè)的賬號(hào):
1.新建個(gè)數(shù)據(jù)表存放郵箱激活碼:
在users/models.py中增加代碼:
class EmailVerifyRecord(models.Model):
"""郵箱激活碼"""
code=models.CharField(max_length=20,verbose_name='驗(yàn)證碼')
email=models.EmailField(max_length=50,verbose_name='郵箱')
send_type=models.CharField(verbose_name='驗(yàn)證碼類(lèi)型',choices=(('register','注冊(cè)'),('forget','忘記密碼')),
max_length=20)
send_time=models.DateTimeField(verbose_name='發(fā)送時(shí)間',default=datetime.now)
class Meta:
verbose_name='郵箱驗(yàn)證碼'
verbose_name_plural=verbose_name
def __str__(self):
return '{0}({1})'.format(self.code,self.email)
在users/adminx.py中注冊(cè)數(shù)據(jù)表:
...... from .models import EmailVerifyRecord ...... class EmailVerifyRecordAdmin(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)
打開(kāi)終端Terminal執(zhí)行更新數(shù)據(jù)庫(kù)命令:
python manage.py makemigrations python manage.py migrate
2.寫(xiě)發(fā)郵件的腳本:在apps/users/新建utils/email_send.py
from random import Random
from users.models import EmailVerifyRecord
from django.core.mail import send_mail
from xyw.settings import EMAIL_FROM
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_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=''
if send_type=='register':
email_title='雪易網(wǎng)注冊(cè)激活鏈接'
email_body='請(qǐng)點(diǎn)擊下面的鏈接激活你的賬號(hào):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 = '請(qǐng)點(diǎn)擊下面的鏈接重置你的密碼: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
3.在settings.py中追加發(fā)送郵件的配置代碼:
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' #同樣是你的郵箱,跟上面都是發(fā)信者郵箱 #我用的新浪的,也可以用別的
4.開(kāi)啟新浪郵箱的smtp服務(wù),不然不能自動(dòng)發(fā)郵件的,步驟如下:
登錄新浪郵箱====》設(shè)置區(qū)====》客戶(hù)端pop/imp/smtp====》Pop3/SMTP服務(wù)====》服務(wù)狀態(tài):開(kāi)啟====》保存
5.增加激活功能
在users/views.py中增加激活類(lèi)ActiveUserView(View)代碼:
......
from .models import EmailVerifyRecord
......
class ActiveUserView(View):
"""激活賬戶(hù)"""
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
user=UserProfile.objects.get(email=email)
user.is_active=True
user.save()
return render(request,'index.html')
6.在users/views.py中
對(duì)注冊(cè)類(lèi) RegisterView(View)增加發(fā)送激活郵件的代碼:
......
from apps.utils.email_send import send_register_email
......
class RegisterView(View):
"""郵箱注冊(cè)"""
def post(self, request):
......
user_profile.save()
#發(fā)送郵件代碼start
send_register_email(email,'register')
#發(fā)送郵件代碼end
return HttpResponse('{"status":"注冊(cè)成功請(qǐng)去郵箱激活!"}')
對(duì)登錄LoginView(View)增加驗(yàn)證賬戶(hù)激活與否的代碼:
class LoginView(View):
"""用戶(hù)登錄"""
def post(self,request):
user_name=request.POST.get("username","")
pass_word=request.POST.get("pwd","")
user=authenticate(username=user_name,password=pass_word)
if user is not None:
#驗(yàn)證賬戶(hù)是否已經(jīng)激活start
if user.is_active:
login(request,user)
return HttpResponse('{"status":"success"}')
else:
return HttpResponse('{"status":"fail","msg":"賬戶(hù)未激活"}')
#驗(yàn)證賬戶(hù)是否已經(jīng)激活end
else:
return HttpResponse('{"status":"fail","msg":"用戶(hù)名或密碼錯(cuò)誤"}')
至此完成了用郵箱注冊(cè)及激活,很多時(shí)候,激活郵件都會(huì)被郵箱自動(dòng)放入垃圾箱,而且從郵件點(diǎn)擊激活鏈接的時(shí)候,還會(huì)被提示一些警告信息,可以說(shuō)通過(guò)郵箱注冊(cè)各種不如通過(guò)短信注冊(cè),但是……省錢(qián)啊!^_^
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- django+vue實(shí)現(xiàn)注冊(cè)登錄的示例代碼
- Django用戶(hù)登錄與注冊(cè)系統(tǒng)的實(shí)現(xiàn)示例
- django 框架實(shí)現(xiàn)的用戶(hù)注冊(cè)、登錄、退出功能示例
- Django實(shí)現(xiàn)auth模塊下的登錄注冊(cè)與注銷(xiāo)功能
- django用戶(hù)注冊(cè)、登錄、注銷(xiāo)和用戶(hù)擴(kuò)展的示例
- Python通過(guò)Django實(shí)現(xiàn)用戶(hù)注冊(cè)和郵箱驗(yàn)證功能代碼
- Django自動(dòng)注冊(cè)tasks及使用方式
相關(guān)文章
用python實(shí)現(xiàn)一幅春聯(lián)實(shí)例代碼
大家好,本篇文章主要講的是用python實(shí)現(xiàn)一幅春聯(lián)實(shí)例代碼,感興趣的同學(xué)趕快來(lái)看一看吧,對(duì)你有幫助的話(huà)記得收藏一下2022-01-01
Python面向?qū)ο蟪绦蛟O(shè)計(jì)類(lèi)的封裝與繼承用法示例
這篇文章主要介紹了Python面向?qū)ο蟪绦蛟O(shè)計(jì)類(lèi)的封裝與繼承用法,結(jié)合實(shí)例形式分析了Python面向?qū)ο蟪绦蛟O(shè)計(jì)中類(lèi)的封裝、繼承相關(guān)概念、原理、用法及操作注意事項(xiàng),需要的朋友可以參考下2019-04-04
基于Django的樂(lè)觀(guān)鎖與悲觀(guān)鎖解決訂單并發(fā)問(wèn)題詳解
這篇文章主要介紹了基于Django的樂(lè)觀(guān)鎖與悲觀(guān)鎖解決訂單并發(fā)問(wèn)題詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-07-07
python tkinter實(shí)現(xiàn)定時(shí)關(guān)機(jī)
這篇文章主要為大家詳細(xì)介紹了python tkinter實(shí)現(xiàn)定時(shí)關(guān)機(jī),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-04-04
python腳本當(dāng)作Linux中的服務(wù)啟動(dòng)實(shí)現(xiàn)方法
今天小編就為大家分享一篇python腳本當(dāng)作Linux中的服務(wù)啟動(dòng)實(shí)現(xiàn)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-06-06
python 文件的基本操作 菜中菜功能的實(shí)例代碼
這篇文章主要介紹了python 文件的基本操作 菜中菜功能,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值 ,需要的朋友可以參考下2019-07-07
Python列表數(shù)據(jù)如何按區(qū)間分組統(tǒng)計(jì)各組個(gè)數(shù)
這篇文章主要介紹了Python列表數(shù)據(jù)如何按區(qū)間分組統(tǒng)計(jì)各組個(gè)數(shù),具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-07-07

