本篇文章主要介紹了django 通過ajax完成信箱使用者註冊、啟用帳號的方法,現在分享給大家,也給大家做個參考。一起過來看看吧
一、圖片驗證碼
django-simple-captcha配置
1.在pycharm中,File====》Settings====》Project:項目名====》Project Interpreter====》+====》搜django-simple-captcha 選擇0.55以上版本,然後點install package 按鈕進行安裝
2.項目名/urls.py中添加代碼:
from django.urls import path,include......from users.views import IndexView......urlpatterns = [ ...... #配置驗證碼 path('captcha/',include('captcha.urls')), #首頁url path('', IndexView.as_view(), name='index'), ......]
3.settings.py中添加一個註冊資訊
INSTALLED_APPS = [ ...... 'captcha']
4.開啟終端Terminal執行更新資料庫命令:
python manage.py makemigrationspython manage.py migrate
5.在users目錄下建立form.py檔案:
from django import formsfrom captcha.fields import CaptchaField......class RegisterForm(forms.Form): """註冊資訊的驗證""" ...... captcha=CaptchaField(error_messages={'invalid':'驗證碼錯誤'}) ......
6.在users/views.py中添加代碼:
from users.form import RegisterFormclass IndexView(View): """首頁""" def get(self,request): register_form=RegisterForm() return render(request,'index.html',{'register_form':register_form})
7.在前端首頁index.html中顯示驗證碼、輸入框
html
<p class="modal fade" id="register" tabindex="-1" role="dialog"> ......<!--模態框中關於註冊的內容start--> <p class="modal-body"> ...... <P><p style="display: inline-block;width:100px;text-align: center"><b >驗證碼:</b></p><!--驗證碼start--> <p class="cap">{{ register_form.captcha }}</p><!--驗證碼end--></P> {% csrf_token %} </form> <p><p style="margin-left: 100px;background-color: orangered;width:150px;text-align: center"><b></b></p></p> </p><!--模態框中關於註冊的內容end--> ......
css
<style> .cap{ display: inline-block; width: 280px; height: 36px; } .cap img{ float: right; }</style>
js 跟重新整理驗證碼相關(需要先引入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郵箱註冊
1.在前端跟註冊綁定的模態框代碼寫成:
html
<p class="modal fade" id="register" tabindex="-1" role="dialog"> ...... <p class="modal-body"> <form id="registerform" action="#" method="post"> <p> <p class="re-input"><b>使用者名稱:</b></p> <input type="text" name="user" placeholder="使用者名稱"> <p class="msg"><b id="user-msg"></b></p> </p> <p> <p class="re-input"><b>郵箱:</b></p> <input type="text" name="email" placeholder="郵箱"> <p class="msg"><b id="email-msg">2222</b></p> </p> <p> <p class="re-input"><b >密碼:</b></p> <input type="password" name="pwd" placeholder="密碼(不少於6位)"> <p class="msg"><b id="pwd-msg">222</b></p> </p> <p> <p class="re-input"><b >確認密碼:</b></p> <input type="password" name="pwd2" placeholder="確認密碼"> <p class="msg"><b id="pwd-msg2">22</b></p> </p> <P><p class="re-input"><b >驗證碼:</b></p> <p class="cap">{{ register_form.captcha }}</p> <p class="msg"><b id="captcha-msg">2</b></p> </P> {% csrf_token %} </form> <p><p style="margin-left: 100px;color: white;background-color: green;width:180px;text-align: center"><b id="active-msg"></b></p></p> ...... <button type="button" class="btn btn-primary" id="registerbtn">確認註冊</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註冊相關的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('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代碼:(要驗證的欄位名跟前端input框的name值要保持一致!)
from django import formsfrom captcha.fields import CaptchaFieldfrom .models import UserProfileclass RegisterForm(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':'驗證碼錯誤'}) def clean(self): '''驗證兩次密碼是否一致''' 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中與註冊相關的代碼:
......from django.http import HttpResponsefrom .models import UserProfile,ShopProfilefrom users.form import RegisterFormfrom django.contrib.auth.hashers import make_passwordimport jsonclass RegisterView(View): """郵箱註冊""" 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":"該使用者名稱或郵箱已被佔用!"}') 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":"註冊成功請去郵箱啟用!"}') msg=register_form.errors msg=json.dumps(msg) return HttpResponse(msg)
4.配置users/urls.py註冊路由:
......from .views import RegisterView.....urlpatterns = [ ...... path('register/',RegisterView.as_view(),name='register'), ...... ]
三、郵箱啟用登入的帳號:
1.建立個資料表存放郵箱啟用碼:
在users/models.py中增加代碼:
class EmailVerifyRecord(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) class Meta: verbose_name='郵箱驗證碼' verbose_name_plural=verbose_name def __str__(self): return '{0}({1})'.format(self.code,self.email)
在users/adminx.py中註冊資料表:
......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)
開啟終端Terminal執行更新資料庫命令:
python manage.py makemigrationspython manage.py migrate
2.寫發郵件的指令碼:在apps/users/建立utils/email_send.py
from random import Randomfrom users.models import EmailVerifyRecordfrom django.core.mail import send_mailfrom xyw.settings import EMAIL_FROMdef 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 strdef 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='雪易網註冊啟用連結' 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
3.在settings.py中追加發送郵件的配置代碼:
EMAIL_HOST='smtp.sina.cn'EMAIL_PORT=25EMAIL_HOST_USER='xxxxxxxx@sina.cn' #你的郵箱EMAIL_HOST_PASSWORD='********'EMAIL_USE_TLS=FalseEMAIL_FROM='xxxxxxx1@sina.cn' #同樣是你的郵箱,跟上面都是發信者郵箱#我用的新浪的,也可以用別的
4.開啟新浪郵箱的smtp服務,不然不能自動發郵件的,步驟如下:
登入新浪郵箱====》設定區====》用戶端pop/imp/smtp====》Pop3/SMTP服務====》服務狀態:開啟====》儲存
5.增加啟用功能
在users/views.py中增加啟用類ActiveUserView(View)代碼:
......from .models import EmailVerifyRecord......class ActiveUserView(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 user=UserProfile.objects.get(email=email) user.is_active=True user.save() return render(request,'index.html')
6.在users/views.py中
對註冊類 RegisterView(View)增加發送啟用郵件的代碼:
......from apps.utils.email_send import send_register_email......class RegisterView(View): """郵箱註冊""" def post(self, request): ...... user_profile.save()#發送郵件代碼start send_register_email(email,'register')#發送郵件代碼end return HttpResponse('{"status":"註冊成功請去郵箱啟用!"}')
對登入LoginView(View)增加驗證賬戶啟用與否的代碼:
class LoginView(View): """使用者登入""" 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:#驗證賬戶是否已經啟用start if user.is_active: login(request,user) return HttpResponse('{"status":"success"}') else: return HttpResponse('{"status":"fail","msg":"賬戶未啟用"}')#驗證賬戶是否已經啟用end else: return HttpResponse('{"status":"fail","msg":"使用者名稱或密碼錯誤"}')
至此完成了用郵箱註冊及啟用,很多時候,啟用郵件都會被郵箱自動放入垃圾箱,而且從郵件點擊啟用連結的時候,還會被提示一些警告資訊,可以說通過郵箱註冊各種不如通過簡訊註冊,但是……省錢啊!^_^