橡皮擦,一個逗趣的互聯網高級網蟲,新的系列,讓我們一起進入 Django 世界,
已經完成的文章
- 滾雪球學 Python 第三輪,Python Web 之 Django 的世界
- 小手哆嗦一下,就能用 Python Django 實作一個微型博客系統
- Django 做個小后臺,細節在完善一點點,滾雪球學 Python 第三階段
- Django QuerySet 就學那么一點點,一點點就夠了
- 看完這篇博客,Python Django 你就學會一半了
- 讓我們一起開發【菜譜系統】吧,滾雪球學 Python 第三輪專案計劃
- 出現吧,Python Web 菜譜系統的首頁,不會前端技術,也能做
滾雪球學 Python 第三輪
- 已經完成的文章
- 八、Django 用戶注冊與登錄
- 8.1 撰寫注冊頁面
- 8.2 注冊頁面的 POST 與 GET 請求
- 8.3 登錄頁面實作
- 8.4 本篇博客小節
八、Django 用戶注冊與登錄
在正式開始本篇博客代碼寫作之前,需要提前準備一下 sqlite3 相關資料表,已經提前撰寫好了 menu、submaterial、ingredients 模型,在命令列執行下述代碼:
> python manage.py makemigrations
Migrations for 'menuapp':
menuapp\migrations\0001_initial.py
- Create model Menu
- Create model SubMaterial
- Create model Ingredients
> python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, menuapp, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
………………
Applying auth.0012_alter_user_first_name_max_length... OK
Applying menuapp.0001_initial... OK
Applying sessions.0001_initial... OK
8.1 撰寫注冊頁面
在 templates/menuapp 目錄下新建 register.html 檔案,該檔案繼承自 frame.html 檔案,具體代碼如下:
frame.html 代碼修改如下:
{% load static %}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<title>{% block title %}{% endblock%}</title>
<link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet" />
</head>
<body>
<nav class="navbar navbar-inverse">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="#">菜譜系統-首頁</a>
</div>
</div>
</nav>
{% block content %}{% endblock %}
<script src="{% static 'js/bootstrap.min.js' %}"></script>
</body>
</html>
register.html 檔案代碼如下:
{% extends "menuapp/frame.html" %} {% block title %} 菜譜系統 ---- 注冊頁面 {%
endblock %} {% block content %}
<div class="container">
<h2 class="form-signin-heading">注冊</h2>
<form class="form-horizontal" role="form">
<div class="form-group">
<label for="username" class="col-sm-2 control-label">用戶名:</label>
<div class="col-sm-6">
<input
type="text"
class="form-control"
id="username"
placeholder="請輸入用戶名"
/>
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-2 control-label">密碼:</label>
<div class="col-sm-6">
<input
type="password"
class="form-control"
id="password"
placeholder="請輸入密碼"
/>
</div>
</div>
<div class="form-group">
<label for="email" class="col-sm-2 control-label">郵箱:</label>
<div class="col-sm-6">
<input
type="text"
class="form-control"
id="email"
placeholder="請輸入郵箱"
/>
</div>
</div>
<div class="form-group">
<label for="master" class="col-sm-2 control-label">權限:</label>
<div class="col-sm-6">
<div class="checkbox">
<label> <input type="checkbox" id="master" />管理員 </label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-6">
<button type="submit" class="btn btn-lg btn-primary btn-block">
注冊
</button>
</div>
</div>
</form>
</div>
{% endblock %}
在正式運行代碼之前,還需要對 urls.py 檔案中的路由進行設定,提前將登錄也設定完畢,代碼如下:
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="defalut"),
path("register", views.register, name="register"),
path("login", views.login, name="login")
]
本部分代碼,你可以直接拷貝到你的專案中,因其都是前端相關知識,你也可以自行完成,在瀏覽器訪問 http://127.0.0.1:8000/register,最終得到的效果如下:

用戶表在下篇博客會有所涉及,本篇博客重點構建出注冊與登錄頁面,
頁面撰寫完畢之后,就要完善對應的后端視圖處理部分,邏輯如下:
- 當用戶訪問注冊頁面時,如果用戶已經登錄,直接跳轉到網站首頁(后續補充邏輯);
- 用戶沒有登錄直接訪問注冊頁面,回傳注冊用表單頁面(本篇博客重點內容),
修改 menuapp/views.py 檔案代碼:
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.urls import reverse
# Create your views here.
def index(request):
return render(request, "menuapp/index.html")
def register(request):
if request.user.is_authenticated:
return HttpResponseRedirect(reverse("default"))
context = {
"active_menu": 'default',
'user': None
}
return render(request, "menuapp/register.html", context)
代碼尤其注意頭部檔案的匯入:
from django.http import HttpResponseRedirect
from django.urls import reverse
request.user.is_authenticated 是用戶登錄驗證,寫完頁面之后,會對其進行說明,
return render(request, "menuapp/register.html", context) 加載 register.html 頁面,其中 context 是向頁面傳遞資料,
8.2 注冊頁面的 POST 與 GET 請求
用戶注冊頁面有兩種請求狀態,這里涉及的是 HTTP 協議相關知識,對于任意一個網頁,都存在多種請求方式,例如注冊頁面的直接訪問獲取表單,就是 GET 請求,當用戶輸入資訊之后,點擊注冊按鈕,此時為 POST 請求,我們對 HTTP 協議不做過多的說明,先完成功能,
首先修改 register.html,在 form 標簽上新增 method 屬性,代碼如下:
<form class="form-horizontal" role="form" method="post"></form>
接下來修改 views.py 中的 register 函式,通過 request 的請求方式不同,處理不同的邏輯,
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.urls import reverse
# Create your views here.
def index(request):
return render(request, "menuapp/index.html")
def register(request):
if request.user.is_authenticated:
return HttpResponseRedirect(reverse("default"))
# 用戶注冊狀態資訊
state = None
# 當用戶提交注冊資訊
if request.method == "POST":
print(request.POST)
username = request.POST.get("username", "")
# 此時需要判斷資料庫中是否存在用戶,目前先不處理
password = request.POST.get("password", "")
email = request.POST.get("email", "")
# 保存注冊資訊到資料庫,本版本先輸出
print(username, password, email)
state = "success" # 表示注冊成功
context = {
"active_menu": 'default',
"user": None,
"state": state
}
return render(request, "menuapp/register.html", context)
撰寫完畢,運行代碼出現如下錯誤,該風險為跨站請求問題,在 form 標簽內部增加如下代碼即可解決,關于原理將在后面講解,
注意下文增加了一個對用戶注冊資訊狀態的驗證,
{% block content %}
<div class="container">
<h2 class="form-signup-heading">注冊</h2>
{% if state == "success" %}
<h2 class="text-success">注冊成功!</h2>
{% endif %}
<form class="form-horizontal" role="form" method="post">
{% csrf_token %}
<div class="form-group">
<label for="username" class="col-sm-2 control-label">用戶名:</label>
<div class="col-sm-6">
<input
type="text"
class="form-control"
id="username"
name="username"
placeholder="請輸入用戶名"
/>
</div>
</div>
</form>
</div>

解決該問題之后,注冊資訊任意輸入,點擊注冊,得到如下頁面,

8.3 登錄頁面實作
借用注冊頁面的相同邏輯,對登錄頁面進行實作,在 templates/menuapp 檔案夾下創建 login.html 檔案,
{% extends "menuapp/frame.html" %} {% block title %} 菜譜系統 ---- 登錄頁面 {%
endblock %} {% block content %}
<div class="container">
<h2 class="form-signup-heading">登錄</h2>
{% if state == "success" %}
<h2 class="text-success">登錄成功!</h2>
{% endif %}
<form class="form-horizontal" role="form" method="post">
{% csrf_token %}
<div class="form-group">
<label for="username" class="col-sm-2 control-label">用戶名:</label>
<div class="col-sm-6">
<input
type="text"
class="form-control"
id="username"
name="username"
placeholder="請輸入用戶名"
/>
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-2 control-label">密碼:</label>
<div class="col-sm-6">
<input
type="password"
class="form-control"
id="password"
name="password"
placeholder="請輸入密碼"
/>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-6">
<button type="submit" class="btn btn-lg btn-primary btn-block">
登錄
</button>
</div>
</div>
</form>
</div>
{% endblock %}
修改 views.py 頁面代碼,實作登錄簡單邏輯部分,
# 登錄視圖
def login(request):
if request.user.is_authenticated:
return HttpResponseRedirect(reverse("default"))
# 登錄狀態資訊
state = None
if request.method == "POST":
username = request.POST.get("username", "")
password = request.POST.get("password", "")
# 通過用戶名和密碼驗證用戶是否可以登錄,步驟先省略
state = "success"
context = {
"active_menu": 'default',
"user": None,
"state": state
}
return render(request, "menuapp/login.html", context)
運行代碼,在瀏覽器訪問 http://127.0.0.1:8000/login,得到如下界面,對其進行用戶名與密碼輸入,獲取登錄成功提示資訊,

8.4 本篇博客小節
本篇博客主要實作了菜譜系統的登錄與注冊頁面,核心要學習的是 urls.py、views.py、templates 中模板檔案 的串聯操作,
相關閱讀
- Python 爬蟲 100 例教程,超棒的爬蟲教程,立即訂閱吧
- Python 游戲世界(更新中,目標文章數 50+,現在訂閱,都是老粉)
- Python 爬蟲小課,精彩 9 講
Django 教程 為什么python不適合開發網站 django框架要學多久 django開源專案 django適合前后端分離嗎 django 用的人多嗎 python web為什么不火 django中文檔案 django搭建web服務器今天是持續寫作的第 126 / 200 天,
如果你想跟博主建立親密關系,可以關注同名公眾號 夢想橡皮擦,近距離接觸一個逗趣的互聯網高級網蟲,
博主 ID:夢想橡皮擦,希望大家點贊、評論、收藏,
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/273275.html
標籤:其他
