User模型
User模型是django自帶的一個用來表示用戶信息的一個模型,這個模型是很重的,用來存儲用戶信息,django爲這個模型提供了很多的方法用來驗證用戶信息,我們也可以使用一些方法擴展User模型來符合自己的需求。
User模型自帶的字段:
mysql> describe auth_user;
+--------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+----------------+
| id | int | NO | PRI | NULL | auto_increment |
| password | varchar(128) | NO | | NULL | |
| last_login | datetime(6) | YES | | NULL | |
| is_superuser | tinyint(1) | NO | | NULL | |
| username | varchar(150) | NO | UNI | NULL | |
| first_name | varchar(30) | NO | | NULL | |
| last_name | varchar(150) | NO | | NULL | |
| email | varchar(254) | NO | | NULL | |
| is_staff | tinyint(1) | NO | | NULL | |
| is_active | tinyint(1) | NO | | NULL | |
| date_joined | datetime(6) | NO | | NULL | |
+--------------+--------------+------+-----+---------+----------------+
11 rows in set (0.00 sec)
可以直接創建超級用戶 python manage.py createsuperuser命令,便會在這個表中創建一行
下面我們做一個用戶登錄和註冊的頁面和用戶信息展示的頁面來體驗一下
author/forms.py
from django import forms
from django.contrib.auth.models import User
class UserForm(forms.Form):
username=forms.CharField()
password=forms.CharField()
author/urls.py
from django.urls import path
from . import views
urlpatterns=[
path('login',views.user_login,name='login'),
path('userprifle',views.userprifle,name='userprifle'),
path('register',views.register,name='register'),
]
author/views.py
from django.shortcuts import render,redirect
from django.http import HttpResponse
# Create your views here.
from django.contrib.auth import authenticate,login
from .forms import UserForm
from django.contrib.auth.models import User
def user_login(request):
if request.method=="GET":
form=UserForm()
context={
'form':form,
}
return render(request,'auth/login.html',context)
else:
user_post=UserForm(data=request.POST)
if user_post.is_valid():
data=user_post.cleaned_data
print(data['username'],data['password'])
user=authenticate(username=data['username'],password=data['password'])
print(user)
if user:
login(request,user)
return redirect("auth:userprifle")
else:
return HttpResponse("密碼錯誤")
else:
return HttpResponse("格式錯誤")
def register(request):
if request.method=="GET":
form=UserForm()
context={
'form':form,
}
return render(request,'auth/register.html',context)
else:
user_post=UserForm(data=request.POST)
if user_post.is_valid():
data=user_post.cleaned_data
User.objects.create_user(username=data['username'],password=data['password'])
return redirect("auth:login")
else:
return HttpResponse("格式錯誤")
def userprifle(request):
user=request.user
if request.user.is_authenticated:
context={
'user':user,
}
return render(request,'auth/userprifile.html',context)
return redirect("auth:login")
templates/auth/login.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div>
<form method="post" action="{% url 'auth:login' %}" role="form" style="height:300px;width:600px;">
{% csrf_token %}
<div class="form-group">
<label>用戶</label>
<input class="form-control" type="text" placeholder="輸入賬戶" name="username">
</div>
<div class="form-group">
<label>密碼</label>
<input class="form-control" type="password" placeholder="輸入密碼" name="password">
</div>
<div class="form-group">
<input type="submit" class="form-control btn btn-primary" value="登錄">
</div>
</form>
</div>
</div>
</body>
</html>
templates/auth/register.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div>
<form method="post" action="{% url 'auth:register' %}" role="form" style="height:300px;width:600px;">
{% csrf_token %}
<div class="form-group">
<label>用戶</label>
<input class="form-control" type="text" placeholder="輸入賬戶" name="username">
</div>
<div class="form-group">
<label>密碼</label>
<input class="form-control" type="password" placeholder="輸入密碼" name="password">
</div>
<div class="form-group">
<input type="submit" class="form-control btn btn-primary" value="註冊">
</div>
</form>
</div>
</div>
</body>
</html>
templates/auth/userprifile.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h1 style="text-align:center;">個人信息</h1>
<br><br><br>
<table class="table table-bordered" >
<thead>
<tr>
<td>用戶</td>
<td>密碼</td>
<td>郵箱</td>
<td>名</td>
<td>姓</td>
<td>註冊日期</td>
<td>最新登錄</td>
</tr>
</thead>
<tbody>
<tr>
<td>{{user.username}}</td>
<td>{{user.password}}</td>
<td>{{user.email}}</td>
<td>{{user.first_name}}</td>
<td>{{user.last_name}}</td>
<td>{{user.date_joined}}</td>
<td>{{user.last_login}}</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
下面看一下我們的結果
login
register
個人信息
主要涉及到的內容有:
user_post=UserForm(data=request.POST)
if user_post.is_valid():
data=user_post.cleaned_data
使用定義的表單類來驗證用戶的輸入是否合法,然後清洗數據,data是一個用戶傳遞post參數的字典。
authenticate(username=data['username'],password=data['password'])
這個函數是用來驗證用戶的登錄是否成功的,如果表中有這個用戶名密碼則返回這個用戶模型對象,否則返回None,可以判斷是否爲None來判斷用戶輸入用戶名和密碼是否正確。
login(request,user)
使用上面的函數可以登錄用戶,會生成一個sessionid在cookie中,在djang_session表中生成用戶的信息,第一個參數是請求對象,第二個參數是一個用戶模型對象
User.objects.create_user(username=data['username'],password=data['password'])
使用上面的代碼可以創建一個用戶,在auth_uesr中會添加一天用戶信息。
user=request.user
表示可以得到一個登錄的模型對象。
request.user.is_authenticated
來判斷這個請求的用戶是否登錄