摘要
django框架本身自帶有登錄注冊,也可以自己寫登錄注冊,下面將介紹這這2種方式實登錄注冊
一、自己寫登錄注冊登出
1.注冊regist
注冊采用的是form表單,提交到數(shù)據(jù)庫,在登錄的時候,查詢數(shù)據(jù)看,看用戶有沒有注冊,如果用戶沒有注冊,則返回注冊頁面注冊
(1)models.py文件里創(chuàng)建相關(guān)的字段: 用戶名字/用戶密碼/cookies攜帶的ticket
from django.db import models# Create your models here.class Users(models.Model): u_name = models.CharField(max_length=10) u_password = models.CharField(max_length=255) u_ticket = models.CharField(max_length=30, null=True) class Meta: db_table = 'day51_user'
(2)urls.py 配置相關(guān)路由
from django.conf.urls import urlfrom uauth import viewsurlpatterns = [ url(r'^regist/', views.regist), url(r'^login/', views.login), url(r'^logout', views.logout)]
(3)views.py 書寫regist方法
導入相關(guān)的包,在regist,login,logout都會使用到
import randomimport timefrom django.contrib import authfrom django.contrib.auth.hashers import make_password,check_passwordfrom django.contrib.auth.models import Userfrom django.http import HttpResponseRedirect, HttpResponsefrom django.shortcuts import renderfrom django.core.urlresolvers import reverse# Create your views here.from uauth.models import Users
如果用戶請求regist方法,則直接跳轉(zhuǎn)到相關(guān)的html頁面。
如果用戶在html頁面點擊了post按鈕,對密碼進行加密后,將數(shù)據(jù)提交到數(shù)據(jù)庫,并返回登錄login頁面。
獲得post提交的表單文字,使用request.POST.get(' ')
def regist(request): if request.method == 'GET': return render(request, 'day6_regist.html') if request.method == 'POST': # 注冊 name = request.POST.get('name') password = request.POST.get('password') # 對密碼進行加密 password = make_password(password) Users.objects.create(u_name=name, u_password=password) return HttpResponseRedirect('/uauth/login/')編寫regist的提交表單, method方法選擇'POST'
文件目錄在templates下[圖片上傳中...(image.png-cc7763-1526105439415-0)]
{%csrf_token%}是針對提交的時候csrf跨域錯誤
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>注冊頁面</title></head><body><form action="" method="POST"> {% csrf_token %} 注冊姓名:<input type="text" name="name"> 注冊密碼:<input type="password" name="password"> <input type="submit" value="提交"></form></body></html>2.登錄login
(1)配置路由urls.py, 與注冊的時候一樣的操作
(2)配置views.py, 編寫login方法
新聞熱點
疑難解答
圖片精選