写点什么

简简单单实现 Python Web 的登录注册页面,还包含一半逻辑。

发布于: 3 小时前

橡皮擦,一个逗趣的互联网高级网虫。新的系列,让我们一起进入 Django 世界。


八、Django 用户注册与登录

在正式开始本篇博客代码写作之前,需要提前准备一下 sqlite3 相关数据表,已经提前编写好了 menusubmaterialingredients 模型,在命令行执行下述代码:


> python manage.py makemigrationsMigrations for 'menuapp':  menuapp\migrations\0001_initial.py    - Create model Menu    - Create model SubMaterial    - Create model Ingredients> python manage.py migrateOperations to perform:  Apply all migrations: admin, auth, contenttypes, menuapp, sessionsRunning 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 pathfrom . 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 renderfrom django.http import HttpResponseRedirectfrom 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 HttpResponseRedirectfrom 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 renderfrom django.http import HttpResponseRedirectfrom 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.pyviews.pytemplates 中模板文件 的串联操作。


博主 ID:梦想橡皮擦,希望大家<font color="red">点赞</font>、<font color="red">评论</font>、<font color="red">收藏</font>。


发布于: 3 小时前阅读数: 2
用户头像

爬虫 100 例作者,蓝桥签约作者,博客专家 2021.02.06 加入

6 年产品经理+教学经验,3 年互联网项目管理经验; 互联网资深爱好者; 沉迷各种技术无法自拔,导致年龄被困在 25 岁; CSDN 爬虫 100 例作者。 个人公众号“梦想橡皮擦”。

评论

发布
暂无评论
简简单单实现 Python Web 的登录注册页面,还包含一半逻辑。