第三百八十五節,Django+Xadmin打造上線標準的在線教育平臺—登陸功能實現javascript
1,配置登陸路由css
from django.conf.urls import url, include # 導入django自在的include邏輯 from django.contrib import admin from django.views.generic import TemplateView # 導入django自帶的TemplateView邏輯 import xadmin # 導入xadmin from app_users.views import deng_lu, zhu_ce, active_code, logout # 導入登陸邏輯處理類 urlpatterns = [ url(r'^xadmin/', xadmin.site.urls), url(r'^index.html', TemplateView.as_view(template_name='index.html'), name='index'), url(r'^register.html', zhu_ce.as_view(), name='register'), url(r'^captcha/', include('captcha.urls'), name='captcha'), url(r'^active/(?P<active_de>.*)/$', active_code.as_view(), name="user_active"), url(r'^login.html', TemplateView.as_view(template_name='login.html'), name='login'), url(r'^deng_lu', deng_lu.as_view(), name='deng_lu'), url(r'^logout', logout.as_view(), name='deng_lu'), ]
2,編寫表單驗證html
#!/usr/bin/env python # -*- coding:utf8 -*- # 表單驗證 from django import forms # 導入Django的表單驗證模塊 from captcha.fields import CaptchaField class deng_lu_forms(forms.Form): # 自定義驗證表單類,繼承Django的表單驗證類 username = forms.CharField( required=True, max_length=20, min_length=2, error_messages={ 'required': '用戶名不能爲空', 'max_length': '用戶名長度不得超過20個字符', 'min_length': '用戶名長度不得少於2個字符', } ) password = forms.CharField( required=True, max_length=20, min_length=2, error_messages={ 'required': '密碼不能爲空', 'max_length': '密碼長度不得超過20個字符', 'min_length': '密碼長度不得少於2個字符', } )
3,在邏輯處理裏,進行表單驗證,若是驗證失敗提示錯誤回填數據,若是驗證成功,獲取驗證後的表單數據,將獲取到的用戶名拿到數據庫查找用戶是否存在,若是不存在提示用戶不存在回填數據,若是存在獲取到用戶密碼,用django的密碼驗證函數check_password(用戶輸入密碼, 數據庫加密密碼),返回布爾值,若是一致返回真,若是密碼正確建立session,向session裏寫入一個表示登陸的鍵值,若是密碼不正確提示密碼錯誤回填數據java
#!/usr/bin/env python # -*- coding:utf8 -*- import io # 導入io模塊 from django.shortcuts import render, HttpResponse, redirect # 導入django向瀏覽器返回方法 from django.views.generic.base import View from django.db.models import F,Q # 導入F和Q from django.contrib.auth.hashers import make_password, check_password # 導入django密碼加密,和密碼驗證 from django.contrib.auth import login # 調用django的登陸函數 from app_users.forms import deng_lu_forms, zhu_ce_forms # 導入登陸頁面表單認證 from app_users.models import Users, Email # 導入數據庫操做 from utils.email_send import send_register_email # 導入郵件發送 class deng_lu(View): def get(self, request): return render(request, 'login.html', {}) def post(self, request): f = deng_lu_forms(request.POST) # 實列化表單認證類,將用戶post提交的數據傳入進行認證 if f.is_valid(): # 判斷認證是否成功 tong_guo = f.cleaned_data # 認證成功,接收用戶數據 username = tong_guo['username'] password = tong_guo['password'] user = Users.objects.filter(username=username) if user: for i in user: mima = i.password pdmima = check_password(password, mima) if not pdmima: tishi = '密碼不正確' return render(request, 'login.html', {'tishi': tishi}) else: request.session["zhuang_tai"] = True # 建立session request.session["username"] = username # request.session["password"] = password return redirect('/index.html') else: tishi = '用戶不存在' return render(request, 'login.html', {'tishi': tishi}) else: # 認證不成功,接收錯誤信息 cuo_wu = f.errors # 接收錯誤信息 return render(request, 'login.html', {'cuo_wu': cuo_wu}) # 將錯誤信息傳到登陸頁面 class logout(View): def get(self, request): try: request.session.flush() except KeyError: pass return redirect('/index.html') def post(self, request): pass
4,settings.py配置sessionpython
# session配置 SESSION_COOKIE_NAME = "_sessionid_" # Session的cookie保存在瀏覽器上時的key,即:sessionid=隨機字符串(默認) SESSION_COOKIE_PATH = "/" # Session的cookie保存的路徑(默認) SESSION_COOKIE_DOMAIN = None # Session的cookie保存的域名(默認) SESSION_COOKIE_SECURE = False # 是否Https傳輸cookie(默認) SESSION_COOKIE_HTTPONLY = True # 是否Session的cookie只支持http傳輸(默認) SESSION_COOKIE_AGE = 1209600 # Session的cookie失效日期(2周)(默認) SESSION_EXPIRE_AT_BROWSER_CLOSE = False # 是否關閉瀏覽器使得Session過時(默認) SESSION_SAVE_EVERY_REQUEST = False # 是否每次請求都保存Session,默認修改以後才保存(默認),默認就好
5,編寫一箇中間件來專門用於用戶登陸帳號狀態檢測,在中間件裏獲取設置的session狀態,經過request.META將登陸狀態向全部頁面注入,在頁面接收這個登陸狀態,判斷若是登陸顯示會員區塊,若是狀態是沒登陸顯示,註冊和登陸區塊jquery
#!/usr/bin/env python # -*- coding:utf8 -*- from django.utils.deprecation import MiddlewareMixin from django.shortcuts import render class zhongjianjian(MiddlewareMixin): def process_request(self, request): print('有請求時執行') # print(request.META) #請求對象內容 #在這裏能夠作ip訪問攔截器 def process_view(self, request, callback, callback_args, callback_kwargs): print('邏輯處理以前執行') zhuang_tai = request.session.get("zhuang_tai") request.META['zhuang_tai'] = zhuang_tai username = request.session.get("username") request.META['username'] = username def process_exception(self, request, exception): print('出錯時執行') # return render(request, 'app1/cuowu.html') print(exception) #作程序出錯時處理 def process_response(self, request, response): print('響應後執行,不管是否出錯') return response
html頁面接收中間件注入的登陸狀態web
<!DOCTYPE html> <html> {% load staticfiles %} {# 啓用靜態文件引用 #} <head> <meta charset="UTF-8"> <meta name="renderer" content="webkit"> <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" > <title>課程機構列表 - 慕學在線網</title> <link rel="stylesheet" type="text/css" href="{% static 'css/reset.css' %}"> {# 啓用靜態文件引用後才能夠 #} <link rel="stylesheet" type="text/css" href="{% static 'css/animate.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> <script src="{% static 'js/jquery.min.js' %}" type="text/javascript"></script> <script src="{% static 'js/jquery-migrate-1.2.1.min.js' %}" type="text/javascript"></script> </head> <body> <section class="headerwrap "> <header> <div class=" header"> <div class="top"> <div class="wp"> <div class="fl"><p>服務電話:<b>33333333</b></p></div> <!--登陸後跳轉--> {{ request.META.zhuang_tai }} {% if request.META.zhuang_tai == True %} <div class="personal"> <dl class="user fr"> <dd>{{ request.META.username }}<img class="down fr" src="/static/images/top_down.png"/></dd> <dt><img width="20" height="20" src="/static/media/image/2016/12/default_big_14.png"/></dt> </dl> <div class="userdetail"> <dl> <dt><img width="80" height="80" src="/static/media/image/2016/12/default_big_14.png"/></dt> <dd> <h2>{{ request.META.username }}</h2> <p>{{ request.META.username }}</p> </dd> </dl> <div class="btn"> <a class="personcenter fl" href="usercenter-info.html">進入我的中心</a> <a class="fr" href="/logout/">退出</a> </div> </div> </div> {% elif request.META.zhuang_tai != True %} <a style="color:white" class="fr registerbtn" href="{% url 'register' %}">註冊</a> <a style="color:white" class="fr loginbtn" href="/login.html">登陸</a> {% endif %} </div> </div>
回填數據以及錯誤提示htmlchrome
回填數據 yanzh.email.value 表單對象.表單字段.value數據庫
<div class="tab-form"> <form id="email_register_form" method="post" action="{% url 'register'%}" autocomplete="off"> <input type='hidden' name='csrfmiddlewaretoken' value='gTZljXgnpvxn0fKZ1XkWrM1PrCGSjiCZ' /> <div class="form-group marb20 {% if cuo_wu.email %}errorput{% endif %} "> <label>郵 箱</label> <input type="text" id="id_email" name="email" value="{{ yanzh.email.value }}" placeholder="請輸入您的郵箱地址" /> </div> <div class="form-group marb8 {% if cuo_wu.password %}errorput{% endif %}"> <label>密 碼</label> <input type="password" id="id_password" name="password" value="{{ yanzh.password.value }}" placeholder="請輸入6-20位非中文字符密碼" /> </div> <div class="form-group marb8 captcha1 {% if cuo_wu.captcha %}errorput{% endif %}"> <label>驗 證 碼</label> {{ yanzhm.captcha }} </div> <div class="error btns" id="jsEmailTips"> {% for key,error in cuo_wu.items %}{{ error }}{% endfor %} #錯誤提示 {% if tishi %}{{ tishi }}{% endif %} </div> <div class="auto-box marb8"> </div> <input class="btn btn-green" id="jsEmailRegBtn" type="submit" value="註冊並登陸" /> <input type='hidden' name='csrfmiddlewaretoken' value='5I2SlleZJOMUX9QbwYLUIAOshdrdpRcy' /> {% csrf_token %} </form> </div>