Python web menu project takes another step forward to learn about the built-in user authentication system from the application layer

Dream eraser 2021-04-07 14:43:37
python web menu project takes

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

Finished articles

Nine 、Django User authentication and authentication , Register login logic implementation , Logout function

9.1 Django User authentication

In the previous blog, we have already talked about Django In the user authentication system has had a preliminary understanding , In this set of user identity authentication system, user accounts can be handled , User group , User permissions ,Cookie I want to solve the problem , Mainly solved Web There are two problems in the system , Certification 、 authentication .

Authentication solves the login problem , Authentication solves the problem of what users can do after logging in .

stay Django There is a built-in User Model , The fields are as follows :

  • username: user name ,150 Within characters ;
  • firstname: First name field ,30 Within characters , Not commonly used in China ;
  • lastname: Last name field ,150 Within characters , Not commonly used in China ;
  • email: Mailbox fields ;
  • password: Password field ;
  • groups: User group fields ;
  • is_staff: Administrator or not , Boolean type ;
  • is_active: Is the user available , Boolean type ;
  • is_superuser: Super administrator field ;
  • last_login: Last login time of the user ;
  • date_joined: User account creation time .

9.1.1 Create user

stay Django In the user system of , Because it involves password management , Not directly through User Class constructor creation User Object and call save Method to create a user .
In general use User Model Manage Provided create_user Method , Pass in parameters to create users .

# The first parameter is the user name , The second parameter is the mailbox , The third parameter is the password 
user = User.objects.create_user("xiangpica","","admin_123")

Change Password , Use the following method .

user = User.objects.get(username="xiangpica")

This is how ordinary users are created , If you want to create a super user , Use createsuperuser Command is enough , Refer to the following steps .

> python createsuperuser
Username (leave blank to use 'administrator'): xiang
Email address:
Password (again):
This password is too short. It must contain at least 8 characters.
This password is too common.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.

9.2 Register login logic implementation

Next, we need to realize the unfinished logic part above, and we want to do the code , The knowledge that needs to be supplemented here is also relatively abstract , The first is in a website , If the user logs in successfully ,Django Will pass cookie Information records the user's login status , And through cookie The information found in session( conversation ) And user information , It's still first , Add logic knowledge .

9.2.1 Registered users enter the library

Before registration , To open the first sqlite3 Take a look at the data , The software used in this eraser is . Open the project directory directly db.sqlite3 The document is available for reference .

Python Web The menu project takes another step forward , Learn about the built-in user authentication system from the application layer
modify The internal logic in the file , modify register.html Page logic , The code is as follows :

# Remember to import the module first 
from django.contrib.auth.models import User
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":
username = request.POST.get("username", "")
password = request.POST.get("password", "")
email = request.POST.get("email", "")
# Determine if the user name exists 
if User.objects.filter(username=username):
state = "user_exist"
n_user = User.objects.create_user(username=username, password=password, email=email)
# Save the registration information to the database
state = "success" # Indicates successful registration 
context = {

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


{% block content %}
<div class="container">
<h2 class="form-signup-heading"> register </h2>
<div class="well">
{% if state == "user_exist" %}
<h2 class="text-warning"> The user has been registered !</h2>
{% endif %} {% if state == "success" %}
<h2 class="text-success"> Registered successfully !</h2>
{% endif %}

Rerun the recipe program , Registered users , For the first time , The second time in registration , Prompt that the user has been registered , At this point, the registration interface completes the minimum available function .

Python Web The menu project takes another step forward , Learn about the built-in user authentication system from the application layer

Query database data , It's found that it has been put into storage .

Python Web The menu project takes another step forward , Learn about the built-in user authentication system from the application layer

9.2.2 User login perfect

Imitate the implementation of registration , Complement the login logic , Focus on modifying File with the login.html file :


{% block content %}
<div class="container">
<h2 class="form-signup-heading"> Sign in </h2>
{% if state == "login_error" %}
<h2 class="text-warning"> Wrong username or password !</h2>
{% endif %}

# Import ahead of time auth modular 
from django.contrib import auth
# 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", "")
# validate logon 
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
return HttpResponseRedirect(reverse("default"))
state = "login_error"
context = {

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

After modification , Run the website , The result is the following error , After repeated inquiries , stay In file , The name of a route is misspelled , Revised as follows :

from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="default"),
path("register", views.register, name="register"),
path("login", views.login, name="login")

The above code successfully solves the following problem .

Python Web The menu project takes another step forward , Learn about the built-in user authentication system from the application layer
The result of normal operation of the above code is , When the user logs in normally , Will jump to the home page , Go back to the login page , Also jump to the home page , The simple understanding is that you can't get into the login page , Unless you manually delete the local cookie.

9.3 User logout

You don't need a page to log out , But it needs to be done Medium logout function .

def logout(request):
# Sign out 
return HttpResponseRedirect(reverse("default"))

The modification is complete After code , Still in Add a new route to log off users .

urlpatterns = [
path("", views.index, name="default"),
path("register", views.register, name="register"),
path("login", views.login, name="login"),
path("logout", views.logout, name="logout")

visit Achieve logout , meanwhile You can visit .

9.4 This blog section

This blog supplements the logic of the login and registration page of the menu system , Based on built-in User Add operation of the model . The article is not very difficult , But there are many core knowledge points , And there are a lot of technical knowledge points that have been postpositioned , These contents will be developed for you in the future , Let's study together .

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 127 / 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]所创,转载请带上原文链接,感谢

  1. 安装python
  2. 按尺寸切片pandas数据集DataFrame到多个文件
  3. Install Python
  4. Slice the pandas dataset dataframe to multiple files by size
  5. python 求最大值、最小值、平均值
  6. Finding maximum, minimum and average in Python
  7. 认识Python解释器和PyCharm编辑器
  8. Know Python interpreter and pycharm editor
  9. Python 小数据池和代码块缓存机制
  10. Python small data pool and code block caching mechanism
  11. python刷题-序列求和
  12. python刷题-圆的面积
  13. Sequence summation in Python
  14. The area of a circle
  15. Python functions, advanced syntax and usage
  16. Teach you to crawl novels in Python! Who can pay for novels these days!
  17. Python入门学习之:10分钟1500访问量
  18. Introduction to Python: 1500 visits in 10 minutes
  19. 数据分析之Pandas合并操作总结
  20. OpenCV-Python 雪花飘落特效
  21. Pandas merge operation summary of data analysis
  22. Opencv Python snowflake falling effect
  23. python logging模块“另一个程序正在使用此文件,进程无法访问。”问题解决办法
  24. Python logging module "this file is being used by another program and cannot be accessed by the process." Problem solving
  25. Mac 下python3 [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed 解决方法
  26. Python 3 [SSL: Certificate] on MAC_ VERIFY_ Failed] certificate verify failed solution
  27. Python学习之解决python下载第三方依赖速度慢的问题
  28. Python learning to solve the problem of slow download speed of third party dependence on Python
  29. python操作Excel文件报lrd.biffh.XLRDError
  30. How to operate excel file with Python lrd.biffh.XLRDError
  31. 2021的挑战与机遇,今年Python数据分析岗位会很香!
  32. The challenge and opportunity of 2021, python data analysis post will be very popular this year!
  33. 【C++简明教程】Python和C++指定元素排序比较
  34. Comparison of Python and C + + specified element sorting
  35. Python Flask使用Nginx做代理时如何获取真实IP
  36. How to get real IP address when Python flash uses nginx as proxy
  37. Python培训出来好找工作吗?好找工作的关键是什么?
  38. Is Python training easy to find a job? What is the key to finding a good job?
  39. 从零开始学python | 什么是Python JSON?
  40. Learn Python from scratch | what is Python JSON?
  41. 用 Python 读写 Excel 表格
  42. Python装饰器高级用法
  43. Reading and writing excel table with Python
  44. Python decorator advanced usage
  45. 从零开始学python | 什么是Python JSON?
  46. Learn Python from scratch | what is Python JSON?
  47. Python with关键字原理详解
  48. Python with keyword principle
  49. python + uiautomator2 实现钉钉工单提交
  50. 一个神级般的 Python 调试神器
  51. Nail work order submission based on Python + uiautomator2
  52. A magic Python debugging artifact
  53. 从零开始学python | 什么是Python JSON?
  54. Learn Python from scratch | what is Python JSON?
  55. 上手Pandas,带你玩转数据(3)-- pandas数据存入文件
  56. Start pandas, take you to play with data (3) -- save pandas data into file
  57. Python能代替shell吗?有什么特点?
  58. Can Python replace shell? What are the features?
  59. Scikit-learn 机器学习库介绍!【Python入门】
  60. Scikit learn machine learning library introduction! [introduction to Python]