您好,登錄后才能下訂單哦!
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 makemigrations python manage.py migrate
5.在users目錄下新建form.py文件:
from django import forms from captcha.fields import CaptchaField ...... class RegisterForm(forms.Form): """注冊信息的驗證""" ...... captcha=CaptchaField(error_messages={'invalid':'驗證碼錯誤'}) ......
6.在users/views.py中添加代碼:
from users.form import RegisterForm class IndexView(View): """首頁""" def get(self,request): register_form=RegisterForm() return render(request,'index.html',{'register_form':register_form})
7.在前端首頁index.html中顯示驗證碼、輸入框
html
<div class="modal fade" id="register" tabindex="-1" role="dialog"> ...... <!--模態框中關于注冊的內容start--> <div class="modal-body"> ...... <P><div ><b >驗證碼:</b></div> <!--驗證碼start--> <div class="cap">{{ register_form.captcha }}</div> <!--驗證碼end--> </P> {% csrf_token %} </form> <p><div ><b></b></div></p> </div> <!--模態框中關于注冊的內容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
<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>用戶名:</b></div> <input type="text" name="user" placeholder="用戶名"> <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 >確認密碼:</b></div> <input type="password" name="pwd2" placeholder="確認密碼"> <div class="msg"><b id="pwd-msg2">22</b></div> </p> <P><div class="re-input"><b >驗證碼:</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 ><b id="active-msg"></b></div></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 forms from captcha.fields import CaptchaField from .models import UserProfile class 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 HttpResponse from .models import UserProfile,ShopProfile from users.form import RegisterForm from django.contrib.auth.hashers import make_password import json class 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 makemigrations python manage.py migrate
2.寫發郵件的腳本:在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='雪易網注冊激活鏈接' 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=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 .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":"用戶名或密碼錯誤"}')
關于django中怎么利用ajax實現郵箱用戶注冊問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業資訊頻道了解更多相關知識。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。