標籤:
Django 使用者認證如果自己不想寫 就可以用django內建的認證
首選匯入模組 models.py
#!/usr/bin/env python#_*_ coding:utf8 _*_from __future__ import unicode_literalsfrom django.db import modelsfrom django.core.exceptions import ValidationErrorfrom django.contrib.auth.models import User
每建立一個使用者都在
class UserProfile(models.Model): user = models.OneToOneField(User) name = models.CharField(max_length=64) school = models.ForeignKey(‘School‘) def __unicode__(self): return self.name
OneToOneField欄位是一對一 不能重複 關聯的關係
使用者認證
首選實現一個簡單的訪問
大項目urls.py
from django.conf.urls import url,includefrom django.contrib import adminfrom app01 import viewsurlpatterns = [ url(r‘^admin/‘, admin.site.urls), url(r‘^$‘, views.index),]
views.py views.py在app01下面
#!/usr/bin/env python
#_*_ coding:utf8 _*_
from django.shortcuts import render,redirect
import models
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
def index(request): return render(request,‘crm/index.html‘)
在crm下面建立index.html 代碼如下:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title></title></head><body>Welcome to Oldboy CRM</body></html>
訪問http://127.0.0.1:8000
認證之後 才能看到頁面資訊如何?呢 這個在實際工作當中經常遇到的 如何?呢 一步一步實現
views.py
#!/usr/bin/env python#_*_ coding:utf8 _*_from django.shortcuts import render,redirectimport modelsfrom django.core.paginator import Paginator, EmptyPage, PageNotAnIntegerfrom app01 import formsfrom django.contrib.auth.decorators import login_required@login_requireddef index(request): return render(request,‘crm/index.html‘)
匯入模組 login_required 在函數下面 加上裝飾器 進行驗證
再次訪問試試
跳轉到http://127.0.0.1:8000/accounts/login/?next=/ 這個連結地址
好 我們來寫個簡單的登入頁面
urls代碼如下
from django.conf.urls import url,includefrom django.contrib import adminfrom app01 import viewsurlpatterns = [ url(r‘^admin/‘, admin.site.urls), url(r‘^$‘, views.index), url(r‘^accounts/login/$‘, views.acc_login),]
views.py代碼如下:
#!/usr/bin/env python
#_*_ coding:utf8 _*_
from django.shortcuts import render,redirect,HttpResponseRedirect
import models
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from app01 import forms
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate,login,logout
@login_requireddef index(request): return render(request,‘crm/index.html‘)def acc_login(request): if request.method == ‘POST‘: print(request.POST) user = authenticate(username=request.POST.get(‘username‘), password=request.POST.get(‘password‘)) if user is not None: login(request,user) return HttpResponseRedirect(‘/‘) else: login_err = "Wrong username or password!" return render(request,‘crm/login.html‘,{‘login_err‘:login_err}) return render(request,"crm/login.html")
建立模板html index.html
index.html代碼如下
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title></title></head><body><h1>Oldboy Welcome</h1>{% block page-container %}Welcome to Oldboy CRM<div>{% if request.user.is_authenticated %}<span>{{ request.user.userprofile.name }}</span>{% else %} <span>登入/註冊</span> {% endif %}</div>{% endblock %}</body></html>
login.html代碼如下
{% extends ‘crm/index.html‘ %}{% block page-container %} <form action="" method="post"> {% csrf_token %} Username: <input type="text" name="username"> Password: <input type="password" name="password"> <input type="submit" value="Log me in"> {% if login_err %} <div style="color: red">{{ login_err }}</div> #前端判斷錯誤 如果錯誤顯示views裡面的內容 {% endif %} </form>{% endblock %}]
好 我們實現了訪問使用者限制
http://127.0.0.1:8000 自動跳轉到
我們輸入正確的使用者名稱 密碼會跳轉到index.html頁面
user = authenticate(username=request.POST.get(‘username‘), password=request.POST.get(‘password‘)) if user is not None: login(request,user) return HttpResponseRedirect(‘/‘)
顯示使用者名稱登入成功名字如何顯示和退出系統
顯示登入成功的名字 需要在最上層顯示
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title></title></head><body><h1>Oldboy Welcome</h1>{% block page-container %}Welcome to Oldboy CRM<div>{% if request.user.is_authenticated %}<span>{{ request.user.userprofile.name }}</span>{% else %} <span>登入/註冊</span> {% endif %}</div><div><a href="/accounts/logout/">退出系統</a></div>{% endblock %}</body></html>
看紅色顯示部分
退出系統代碼 看黃色部分 前端
url代碼如下
from django.conf.urls import url,includefrom django.contrib import adminfrom app01 import viewsurlpatterns = [ url(r‘^admin/‘, admin.site.urls), url(r‘^$‘, views.index), url(r‘^accounts/login/$‘, views.acc_login), url(r‘^accounts/logout/$‘, views.acc_logout),]
views.py代碼如下:
def acc_logout(request): logout(request) return HttpResponseRedirect(‘/‘)
點擊退出系統 跳轉到
<a href="/accounts/logout/">退出系統</a>
def acc_logout(request): logout(request) return HttpResponseRedirect(‘/‘) 跳轉到登入頁面
Django 使用者認證及OneToOneField