Simple implementation of Python web login registration page, but also contains half of the logic.

Dream eraser 2021-04-06 01:31:36
simple implementation python web login


Eraser , A funny senior Internet bug . New series , Let's go into Django The world .

Finished articles

8、 ... and 、Django User registration and login

Before we start writing this blog code , You need to prepare in advance sqlite3 Relevant data sheets , It's written in advance menusubmaterialingredients Model , Execute the following code on the command line :

> 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 Write registration page

stay templates/menuapp New under the directory register.html file , This file is inherited from frame.html file , The specific code is as follows :
frame.html The code is modified as follows

{% 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="#"> Menu system - home page </a>
</div>
</div>
</nav>
{% block content %}{% endblock %}
<script src="{% static 'js/bootstrap.min.js' %}"></script>
</body>
</html>

register.html The document code is as follows :

{% extends "menuapp/frame.html" %} {% block title %} Menu system ---- Registration page {%
endblock %} {% block content %}
<div class="container">
<h2 class="form-signin-heading"> register </h2>
<form class="form-horizontal" role="form">
<div class="form-group">
<label for="username" class="col-sm-2 control-label"> user name :</label>
<div class="col-sm-6">
<input
type="text"
class="form-control"
id="username"
placeholder=" Please enter a user name "
/>
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-2 control-label"> password :</label>
<div class="col-sm-6">
<input
type="password"
class="form-control"
id="password"
placeholder=" Please input a password "
/>
</div>
</div>
<div class="form-group">
<label for="email" class="col-sm-2 control-label"> mailbox :</label>
<div class="col-sm-6">
<input
type="text"
class="form-control"
id="email"
placeholder=" Please enter email address "
/>
</div>
</div>
<div class="form-group">
<label for="master" class="col-sm-2 control-label"> jurisdiction :</label>
<div class="col-sm-6">
<div class="checkbox">
<label> <input type="checkbox" id="master" /> Administrators </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">
register
</button>
</div>
</div>
</form>
</div>
{% endblock %}

Before running the code , Also need to urls.py Set the route in the file , The login is also set up in advance , The code is as follows :

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")
]

This part of the code , You can copy it directly into your project , Because it's all front-end knowledge , You can also do it yourself , Access in browser http://127.0.0.1:8000/register, The result is as follows :
 Simply achieve Python Web Login registration page of , And half the logic .
The user list will be covered in the next blog , This blog focuses on building a registration and login page .

After the page is written , It is necessary to improve the corresponding back-end view processing part . The logic is as follows :

  • When a user visits the registration page , If the user is already logged in , Jump directly to the home page of the website ( Follow up supplementary logic );
  • The user did not log in and directly visited the registration page , Return to the registration form page ( Key content of this blog ).

modify menuapp/views.py File code :

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)

The code pays special attention to the import of header files :

from django.http import HttpResponseRedirect
from django.urls import reverse

request.user.is_authenticated It's user login authentication , After writing the page , It will be explained .
return render(request, "menuapp/register.html", context) load register.html page , among context It's passing data to the page .

8.2 Of the registration page POST And GET request

The user registration page has two request States , What's involved here is HTTP Protocol related knowledge , For any web page , There are many ways to request , For example, direct access to the registration page to get the form , Namely GET request , When the user enters the information , Click the register button , This is the case POST request , We are right. HTTP The agreement doesn't make too much explanation , Finish the function first .

The first change register.html, stay form Add... To the label method attribute , The code is as follows :

<form class="form-horizontal" role="form" method="post"></form>

I'm going to modify views.py Medium register function , adopt request There are different ways to request , Deal with different logic .

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"))
# User registration status information 
state = None
# When the user submits the registration information 
if request.method == "POST":
print(request.POST)
username = request.POST.get("username", "")
# At this time, we need to determine whether there are users in the database , At present, we will not deal with 
password = request.POST.get("password", "")
email = request.POST.get("email", "")
# Save the registration information to the database , This version first outputs 
print(username, password, email)
state = "success" # Indicates successful registration 
context = {

"active_menu": 'default',
"user": None,
"state": state
}
return render(request, "menuapp/register.html", context)

Finished writing , Run the code with the following error , The risk is the cross site request problem , stay form Add the following code inside the tag to solve the problem , The principle will be explained later .
Note that a verification of the user's registration status is added below .

{% block content %}
<div class="container">
<h2 class="form-signup-heading"> register </h2>
{% if state == "success" %}
<h2 class="text-success"> Registered successfully !</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"> user name :</label>
<div class="col-sm-6">
<input
type="text"
class="form-control"
id="username"
name="username"
placeholder=" Please enter a user name "
/>
</div>
</div>
</form>
</div>

 Simply achieve Python Web Login registration page of , And half the logic .
After solving the problem , Enter the registration information at will , Click registration , Get the following page .
 Simply achieve Python Web Login registration page of , And half the logic .

8.3 Login page to achieve

Borrow the same logic from the registration page , Implement the login page . stay templates/menuapp Create under folder login.html file .

{% extends "menuapp/frame.html" %} {% block title %} Menu system ---- The login page {%
endblock %} {% block content %}
<div class="container">
<h2 class="form-signup-heading"> Sign in </h2>
{% if state == "success" %}
<h2 class="text-success"> Login successful !</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"> user name :</label>
<div class="col-sm-6">
<input
type="text"
class="form-control"
id="username"
name="username"
placeholder=" Please enter a user name "
/>
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-2 control-label"> password :</label>
<div class="col-sm-6">
<input
type="password"
class="form-control"
id="password"
name="password"
placeholder=" Please input a password "
/>
</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">
Sign in
</button>
</div>
</div>
</form>
</div>
{% endblock %}

modify views.py Page code , Realize the simple logic part of login .

# Login view 
def login(request):
if request.user.is_authenticated:
return HttpResponseRedirect(reverse("default"))
# Login status information 
state = None
if request.method == "POST":
username = request.POST.get("username", "")
password = request.POST.get("password", "")
# Verify whether the user can log in through the user name and password , Omit the steps first 
state = "success"
context = {

"active_menu": 'default',
"user": None,
"state": state
}
return render(request, "menuapp/login.html", context)

Run code , Access in browser http://127.0.0.1:8000/login, Get the following interface , Enter the user name and password , Get the successful login information .
 Simply achieve Python Web Login registration page of , And half the logic .

8.4 This blog section

This blog mainly realizes the menu system login and registration page , The core thing to learn is urls.pyviews.pytemplates In the template file In series operation .

Related reading

  1. Python Reptiles 100 Example tutorial , Great crawler tutorial , Subscribe now
  2. Python Game world ( Updating , Target number of articles 50+, Now subscribe to , It's all old powder )
  3. Python Reptile lesson , wonderful 9 speak

Today is the first day of continuous writing 126 / 200 God .
If you want to build a close relationship with a blogger , You can pay attention to the official account number of the same name Dream eraser , Close contact with a funny advanced Internet bug .
Blogger ID: Dream eraser , I hope you all. give the thumbs-up Comment on Collection .

Django course Why? python Not suitable for developing websites django How long does it take to learn the framework django Open source project django Suitable for front and rear end separation django Do you use a lot of people python web Why not fire django Chinese document django build web The server
版权声明
本文为[Dream eraser]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/04/20210406013042889Y.html

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database