Django用戶注冊、登錄、注銷(一)

使用Django自帶的用戶認證系統編寫認證、登錄、注銷基本功能

功能:

使用Django默認的User表

1)注冊

  判斷是否已存在此用戶,存在的話提示報錯“用戶已存在”;

  判斷兩次輸入的密碼是否一致,不一致的話提示報錯“密碼不一致”。

 實現報錯提示的方式有兩種:

  第一種:在form表單中使用clean_函數進行定義判斷函數,在views中進行的is_valid()判斷時進行校驗,并獲取錯誤傳送到模板中顯示在前端。

  第二種:直接在views視圖中判斷

2)登錄

  登錄成功,跳轉到主頁index;

  登錄不成功,初始化登錄頁面;

  跳轉到注冊頁面。

3)主頁

  直接訪問主頁,用戶沒有登錄的話跳轉到登錄頁面; 

  用戶已登錄顯示用戶登錄名。

4)注銷

  清除登錄的session,退出登錄

項目目錄結構:

mysite/setting設置

注冊應用:

更改時區和語言設置

from django.contrib import admin
from django.urls import path
from django.conf.urls import url,include
urlpatterns = [path('admin/', admin.site.urls),url(r'^djauth/',include('djauth.urls',namespace='djauth')),]
mysite/urls.py
from django.urls import re_path
from . import views
app_name='djauth'
urlpatterns=[re_path(r'^$',views.index),re_path(r'register/$',views.register,name="register"),re_path(r'login/$',views.login_view,name="login"),re_path(r'logout/$',views.logout_view,name="logout"),
]
djauth/urls.py
from django import forms
from django.contrib.auth.models import User
class login_form(forms.Form):username=forms.CharField(max_length=30)password=forms.CharField(widget=forms.PasswordInput)class register_form(forms.Form):username=forms.CharField(max_length=30,label="姓名")email=forms.EmailField()password=forms.CharField(widget=forms.PasswordInput,min_length=3,label="密碼")password_re=forms.CharField(widget=forms.PasswordInput,min_length=3,label="確認密碼")#第一種報錯方式,使用form表單,views中捕捉##clean_字段,,在視圖views使用is_valid時自動嚴重表單字段的有效性# def clean_username(self):#     cd=self.cleaned_data#     user=User.objects.filter(username=cd['username'])#     if user:#         raise forms.ValidationError('用戶已存在')#     return cd['username']# def clean_password_re(self):#     cd=self.cleaned_data#     if cd['password']!=cd['password_re']:#         raise forms.ValidationError("密碼不一致")#     return cd['password_re']
djauth/forms.py
from django.shortcuts import render,redirect,reverse
from django.http import HttpResponse
import time
from django.contrib import auth
from django.contrib.auth.models import User
from . import forms#訪問index首頁前先判斷用戶是否登錄,沒有登錄的話需要跳轉到login登錄
#實現方式一:判斷request.user.is_authenticated
# def index(request):
#     #驗證用戶是否登錄成功
#     if  request.user.is_authenticated:
#         # request.user.username;;獲取登錄用戶名
#         print("UserAuth:",request.user.username)
#         return render(request,"djauth/index.html")
#     else:
#         return redirect("/djauth/login/")
#實現方式二:使用@login_required裝飾器
#login_required裝飾器會先判斷用戶是否登錄,如果沒有登錄則自動跳轉到login_url路徑,
#默認跳轉路徑是/accounts/login/,并在登錄后跳轉到原先的請求路徑;如請求路徑/djauth、,
#默認跳轉路徑為/accounts/login/?next=/djauth/#示例:
#沒有login_url
#[13/Dec/2018 14:40:16] "GET /djauth/ HTTP/1.1" 302 0
#302跳轉
#[13/Dec/2018 14:40:16] "GET /accounts/login/?next=/djauth/ HTTP/1.1"
#指定loging_url
#[13/Dec/2018 14:41:31] "GET /djauth/ HTTP/1.1" 302 0
#[13/Dec/2018 14:41:32] "GET /djauth/login/?next=/djauth/ HTTP/1.1" 200 725
#[13/Dec/2018 14:42:35] "POST /djauth/login/?next=/djauth/ HTTP/1.1" 302 0
#302登錄成功后自動跳轉
#[13/Dec/2018 14:42:35] "GET /djauth/ HTTP/1.1" 200 263
from django.contrib.auth.decorators import login_required
@login_required(login_url="/djauth/login/")
def index(request):return render(request,"djauth/index.html")def register(request):errors=[]if request.method=='POST':#初始化表單RegisterForm=forms.register_form(request.POST)#驗證表單的輸入是否有效,格式是否正確if RegisterForm.is_valid():# 第一種報錯方式,捕捉form表單的報錯##獲取表單有效的值# Register=RegisterForm.cleaned_data##創建用戶# user=User.objects.create_user(username=Register['username'],#                               password=Register['password'],#                               email=Register['email']#                               )##保存# user.save()# return HttpResponse("注冊成功")##獲取form表單clean函數中raise的錯誤#errors=RegisterForm.errors#第二種報錯方式,直接在views中判斷Register=RegisterForm.cleaned_data#判斷用戶是否存在user_exist=User.objects.filter(username=Register['username']).exists()if user_exist:errors.append("用戶已存在")if Register['password']!=Register['password_re']:errors.append("密碼不一致")else:user=User.objects.create_user(username=Register['username'],password=Register['password'],email=Register['email'])user.save()return HttpResponse("注冊成功")#初始化表單RegisterForm=forms.register_form()return render(request,"djauth/register.html",{"RegisterForm":RegisterForm,"errors":errors})def login_view(request):error=[]curtime=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())if request.method=='POST':LoginForm=forms.login_form(request.POST)if LoginForm.is_valid():Account=LoginForm.cleaned_data#驗證User表中用戶的賬號密碼是否正確,驗證通過,返回用戶名,不通過,返回Noneuser=auth.authenticate(username=Account['username'],password=Account['password'])if user is not None:#判斷賬戶是否活躍if user.is_active:auth.login(request,user)return redirect("/djauth/")else:error.append("用戶無效")else:error.append("賬號或密碼錯誤")else:LoginForm=forms.login_form()return render(request,'djauth/login.html',{"LoginForm":LoginForm,"curtime":curtime,"error":error})def logout_view(request):#清除session,登出
    auth.logout(request)return redirect("/djauth/login")
djauth/views.py
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>{% block title %}{% endblock %}</title>
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>
djauth/templates/djauth/base.html
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>首頁</title>
</head>
<body>
<h1>首頁</h1>
<!--獲取登錄用戶名:request.user.username或user.username-->
{% if request.user.is_authenticated %}{{ user.username }}
{% endif %}<p><a href="{% url 'djauth:logout' %}">退出</a></p>
</body>
</html>
djauth/templates/djauth/index.html
{% extends "djauth/base.html" %}{% block title %}
Login Page
{% endblock %}{% block content %}
<h1>Login Page</h1>{% if error %}{{ error }}{% endif %}<p>時間:{{ curtime }}</p><form action="" method="post">{% csrf_token %}{{ LoginForm.as_p }}<input type="submit" value="Login"></form><p>沒有賬號?點擊<a href="{% url 'djauth:register' %}">注冊</a></p>
{% endblock %}
djauth/templates/djauth/login.html
{% extends "djauth/base.html" %}
{% block title %}
Register Page
{% endblock %}{% block content %}
<h1>Register Page</h1>{% if errors %}<p>{{ errors }}</p>{% endif %}<form action="" method="post">{% csrf_token %}{% for foo in RegisterForm %}<p>{{ foo.label_tag }}{{ foo }} {{ errors.foo }}</p>{% endfor %}<input type="submit" value="注冊"></form>
{% endblock %}
djauth/templates/djauth/register.html

?

轉載于:https://www.cnblogs.com/kikkiking/p/10113154.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/278684.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/278684.shtml
英文地址,請注明出處:http://en.pswp.cn/news/278684.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

1月3日學習內容整理:modelform

1、modelform本質上還是form組件 2、引入 from django.forms import ModelForm 3、創建 class Form(ModelForm): class Meta: modelBook Book就是models.py中定義的類&#xff0c;也就是表 firelds"_ _all_ _" 代表繼承Book表中的所有字…

如何在PowerPoint中自動調整圖片大小

PowerPoint can automatically resize an image to fit a shape. You can also resize multiple images already in your presentation to all be the same size. Here’s how it works. PowerPoint可以自動調整圖像大小以適合形狀。 您還可以將演示文稿中已有的多個圖像調整為…

vue目錄結構

vue目錄結構參考一參考二參考三參考一 目錄一級二級bulid項目構建的一些 js 文件config配置文件項&#xff0c;index.js 比較重要&#xff0c;打包上線需要修改配置dist項目打包后的文件node_modulesnpm安裝包位置src項目的開發目錄-assets圖片、字體等資源-components公共組件…

js獲取當前日期

var myDate new Date(); myDate.getYear(); //獲取當前年份(2位) myDate.getFullYear(); //獲取完整的年份(4位,1970-????) myDate.getMonth(); //獲取當前月份(0-11,0代表1月) myDate.getDate(); //獲取當前日(1-31) myDate.getDay(); //獲取當前星期X(0-6,0代表星期天) …

如何在不支付Adobe Photoshop費用的情況下處理Camera Raw

You might think that you need expensive software to take advantage of Camera RAW—something like Photoshop or the more modestly priced Lightroom. Fortunately there is freeware that can help you achieve professional results without professional costs. 您可能…

eclipse 代碼提示后面的百分比是什么意思?

簡而言之&#xff0c;就是提示你其他人&#xff08;開發人員&#xff09;在此情形下使用該方法百分比&#xff0c;最常用方法百分比 見http://www.eclipse.org/recommenders/manual/#d0e32 Call Completion The Call Completion engine, for example, provides you with recomm…

python實現關聯規則

代碼中Ci表示候選頻繁i項集&#xff0c;Li表示符合條件的頻繁i項集    # codingutf-8    def createC1(dataSet): # 構建所有1項候選項集的集合    C1 []    for transaction in dataSet:    for item in transaction:    if [item] not in C1:   …

Progressive Web App(PWA)

Progressive Web App一、 PWA 宣傳 &#xff1a; Reliable &#xff08; 可靠的 &#xff09;、Fast&#xff08; 快速的 &#xff09;、Engaging&#xff08; 可參與的 &#xff09;二、什么是Progressive三、為什么我們需要Progressive Web App一、 PWA 宣傳 &#xff1a; Re…

travis-cli 使用

1. 添加項目登錄 travis 選擇對應項目即可 2. 添加持續集成文件.travis.ymllanguage: node_js node_js:- "node" before_install: - npm install -g jspm - jspm install script: - jspm bundle lib/main --inject備注&#xff1a;這是一個jspm 項目 3. 構建travis 是…

在Windows Media Center中收聽超過100,000個廣播電臺

A cool feature in Windows 7 Media Center is the ability to listen to local FM radio. But what if you don’t have a tuner card that supports a connected radio antenna? The RadioTime plugin solves the problem by allowing access to thousands of online radio …

vue項目中按需引入viewUI

viewUI一、按需引入二、忽略eslint編譯器檢測和編譯檢測1.忽略編譯器檢測2.編譯器中忽略一、按需引入 npm install babel-plugin-import --save-dev // .babelrc1 { “plugins”: [[“import”, { “libraryName”: “view-design”, “libraryDirectory”: “src/components”…

IntelliJ IDEA——數據庫集成工具(Database)的使用

idea集成了一個數據庫管理工具&#xff0c;可以可視化管理很多種類的數據庫&#xff0c;意外的十分方便又好用。這里以oracle為例配置。 1、配置 在窗口的右邊有個Database按鈕&#xff0c;點擊。 如果沒有&#xff0c;請點擊上方的View(視圖)-Tool Windows(工具窗口)-Database…

為什么VC經常輸出燙燙燙燙燙燙燙燙

在Debug 模式下&#xff0c; VC 會把未初始化的棧內存全部填成0xcc&#xff0c;當字符串看就是 燙燙燙燙……會把未初始化的堆內存全部填成0xcd&#xff0c;當字符串看就是 屯屯屯屯……可以讓我們方便地看出那些內存沒初始化但是Release 模式下不會有這種附加動作&#xff0c;…

代碼評審會議_如何將電話會議(和訪問代碼)另存為聯系人

代碼評審會議Dialing a conference call doesn’t have to be a tedious process. Your iPhone or Android phone can automatically dial into the call and enter a confirmation code for you. You just have to create a special type of contact. 撥打電話會議不一定是一個…

Vuex使用總結

Vuex綜合使用一、倉庫1.主倉庫2.子倉庫二、使用1.全局&#xff08;index.js和未開啟命名空間的子倉庫&#xff09;2.子倉庫&#xff08;子倉庫定義了namespaced: true&#xff09;&#xff0c;倉庫名&#xff1a;home3.使用strict嚴格模式&#xff08;建議&#xff09;三、批量…

好未來提前批

好未來提前批(注&#xff1a;轉載于牛客網) 一面&#xff08;25minutes&#xff09; 1.創建對象的幾種方式2.Jsp九大隱式對象3.自己封裝的持久層框架用過么4.Spring ioc讓你實現怎么實現呢&#xff08;工廠反射&#xff0c;我半年前寫過&#xff0c;忘記了&#xff09;5.Aop的實…

Nginx服務學習(6)-日志模塊

日志模塊的說明 日志的默認路徑&#xff1a;error_log /var/log/nginx/error.log warn; warn是指日志的等級&#xff0c;一般有debug, info, notice, warn, error, crit。access_log /var/log/nginx/access.log main; main是指訪問日志記錄的格式信息&#xff0c;在…

vue mock模擬后臺接口數據

vue mock一、Json server二、Mock 服務1.安裝2.創建 Mock3.main.js引入4.組件中axure請求一、Json server 輕量級&#xff0c;將已有的json文件跑在服務器上供前端調用 npm install -g json-server 啟動JSON數據服務器&#xff1a; json-server --watch json文件名 或 json-se…

個人站立會議-----20181216

繼續閱讀測量程序設計這本書&#xff0c;并根據測量平差基礎中的知識編寫多個已知點水準網的間接平差&#xff0c;結果總是差些&#xff0c;詢問過老師之后&#xff0c;才知道在程序中要增加檢索閉合歡或閉合線段的條件&#xff0c;正在改進中 轉載于:https://www.cnblogs.com/…

使用iOS 4越獄iPhone或iPod Touch

In case you haven’t heard the news over the past couple of days, there is now an incredibly easy way to jailbreak your iPod Touch or iPhone running iOS 4. Here we will take a look at how easy the process is. 如果您在過去的幾天里沒有聽到這個消息&#xff0c…