這篇文章主要介紹了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
<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>
$("#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); } } }); });
$("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
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
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' #同样是你的邮箱,跟上面都是发信者邮箱 #我用的新浪的,也可以用别的
...... 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')
...... 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":"注册成功请去邮箱激活!"}')
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完成信箱使用者註冊、啟動帳號的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!