Django's simple user system (3)

Single. 2020-11-08 18:17:46
django simple user


1. Overall design idea

A simple user management system , Including but not limited to the following functions :

  • Users increase : For new users ;
  • User query : Used to query user information ;
  • The user to change : Used to modify user information ;
  • User deletion : Used to delete user information ;

The most basic functions include adding 、 Delete 、 Change 、 Checked .

Want to build a system , In the early stage, we must design a set of ideas , Please take your seats according to the above figure .

below , How to start the actual combat ...

To highlight the , Do it Do it Do it ...

2. Build a simple user system

If any student has not learned the last two articles , Please go and study , Let's look at this article again .

2.1 Configuration model Model

hello\models.py

Create a class (class) object , This is equivalent to a table in the data (table).

# Create database User surface
class User(models.Model):
# Gender , Tuples are used for drop-down boxes
sex = ((0, ' male '), (1, ' Woman '))
# user name
username = models.CharField(max_length=20, help_text=' user name ')
# User password
password = models.CharField(max_length=16, help_text=' User password ')
# sex Medium 0,1 It's stored in the database , Chinese men and women are in web Front end display
sex = models.IntegerField(choices=sex, null=True, blank=True)
# Phone number
phone = models.CharField(max_length=11, help_text=' Phone number ')
# Object to get the return value as user name
def __str__(self):
return self.username

2. 2 Write to database :

The background will be converted to sql Statement is written to the database , Doesn't it look convenient , You don't have to understand sql 了 , This is also ORM The power of .

(py369) [root@localhost devops]# python manage.py makemigrations hello
Migrations for 'hello':
hello/migrations/0005_auto_20201105_2336.py
- Create model User
- Alter field id on devices
(py369) [root@localhost devops]# python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, hello, sessions
Running migrations:
Applying hello.0005_auto_20201105_2336... OK

2.3 Database validation table :

I'm through Navicat Premium Tools connect to the database , Visual view , You can use any tool .

2.4 route URL To configure :

hello\urls.py

name='xxxx', This is the use of a namespace , This is often used in templates :hello:adduser, Equate to hello/adduser.html, The advantage is that you don't have to worry about your path Change at will .

from django.urls import path
from django.urls import re_path
from hello import view
app_name = 'hello'
urlpatterns = [
# FBV, By way of function , We will increase, delete, and change inspections
# increase
path('adduser/', view.adduser, name="adduser"),
# Inquire about
path('showuser/', view.showuser, name="showuser"),
# modify
re_path('edituser/(?P<pk>[0-9]+)?/', view.edituser, name="edituser"),
# Delete
re_path('deluser/(?P<pk>[0-9]+)?/', view.deluser, name="deluser"),
]

2.5 Users increase

Background execution script configuration :

hello\view.py

from django.shortcuts import render
from django.http import HttpResponse, QueryDict
from django.shortcuts import get_object_or_404
from django.http import Http404
from hello.models import User
import traceback
# User added function
def adduser(request):
msg = {}
if request.method == 'POST':
try:
print(request.POST)
# Converting data into dictionary format
data = request.POST.dict()
# Write data to the database at one time
User.objects.create(**data)
msg = {'code':0, 'result':' Successfully added user .'}
except:
msg = {'code':1, 'result':' Failed to add user :'.format(traceback.format_exc())}
return render(request, "hello/adduser.html", {'msg':msg})

View template configuration :

templates\hello\adduser.html

<!-- Inherit the master -->
{% extends "base.html" %}
<!-- rewrite title The content of -->
{% block title %} Users add {% endblock %}
<!-- rewrite body The content of -->
{% block body %}
<!-- Show success or failure information -->
{% if msg.code == 0 %}
<p style="color: green"> {{ msg.result }}</p>
{% else %}
<p style="color: red"> {{ msg.result }}</p>
{% endif%}
<div class="container">
<h2 style="color: #666666"> Add user information </h2><br>
<!-- Forms -->
<form method="post" action="">
user :
<input type="text" name="username">
<br><br>
password :
<input type="password" name="password">
<br><br>
cell-phone number :
<input type="text" minlength="11" maxlength="11" name="phone">
<br><br>
Gender :
<input type="radio" name="sex" value="0" checked> male
<input type="radio" name="sex" value="1" checked> Woman
<br><br>
<button type="submit"> Submit </button>
<button type="reset"> Reset </button>
</form>
</div>
{% endblock%}

The effect of the front-end display is as follows :

Open the browser , Enter the following link format :http://ip/hello/adduser

User submit , Background database validation :

After filling in the information carefully , Click on the submit , If you succeed, it will show Successfully added user , In addition, you can go backstage DB To verify the .

I created 6 individual user , I am capricious. .

remarks : Please ignore that the password in the database table is plaintext , It will be ciphertext in the following actual combat , Don't worry about password leaks .

2.6 User query

Background execution script configuration :

hello\view.py

# New code block
# User view function
def showuser(request):
# http://192.168.8.130:8888/hello/showuser/?keyword=test001
# Get key position parameters ,get Get unique value ,'' Represents the default parameter , Prevent error reporting
keyword = request.GET.get('keyword', '')
# Get all the data
users = User.objects.all()
# If the key position parameter is not empty
if keyword:
# The user name is case insensitive
users = users.filter(username__icontains=keyword)
# return Return two parameters 'users' and 'keyword' To the front end
return render(request, 'hello/showuser.html', {'users':users, 'keyword':keyword})

View template configuration :

templates\hello\showuser.html

<!-- Inherit the master -->
{% extends "base.html" %}
<!-- rewrite title The content of -->
{% block title %} User query {% endblock %}
<!-- rewrite body The content of -->
{% block body %}
<div class="container">
<h2 style="color: #666666"> Query user information </h2><br>
<!-- Search box -->
<!-- action Redirect to http://ip/hello/showuser,showuser It's a namespace name-->
<!-- 'hello:showuser' Equate to http://ip/hello/showuser/ -->
<!-- name='keyword' Express http://ip/hello/showuser/?keyword='test001' Medium keyword Parameters -->
<!-- value Show in text box -->
<form action="{% url 'hello:showuser' %}">
<input type="text" name="keyword" value="{{ keyword }}" placeholder=" Please enter the information you want to query ">
<button type="submit"> Search for </button>
</form>
<!-- form -->
<table border="1">
<thead>
<tr>
<th> ID </th>
<th> user name </th>
<th> password </th>
<th> Phone number </th>
<th> Gender </th>
<th> operation </th>
</tr>
</thead>
<br>
<tbody>
{% for user in users %}
<tr>
<td> {{ user.id }} </td>
<td> {{ user.username }} </td>
<td> {{ user.password }} </td>
<td> {{ user.phone }} </td>
<td> {% if user.sex == 0 %} male {% elif user.sex == 1 %} Woman {% else %}none {% endif %} </td>
<td>
<a href="{% url 'hello:edituser' user.id %}"> to update </a>
<a href="{% url 'hello:deluser' user.id %}"> Delete </a>
<!-- Equivalent to the following , But this is not recommended :-->
<!-- <a href="/hello/edituser/{{user.id}}/"> to update </a>-->
<!-- <a href="/hello/deluser/{{user.id}}/"> Delete </a>-->
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endblock%}

The effect of the front-end display is as follows :

Query the user , It's shown as follows :

At this time, the backstage is through username To filter , Later we will pass Q Method to filter multiple fields .

2.7 The user to change

Background execution script configuration :

hello/view.py

Key points : Whether it's user query or delete , The point is ID ( The primary key in the database ) To operate , Don't use other fields .

# New code , User modification function
def edituser(request, **kwargs):
msg = {}
pk = kwargs.get('pk', '')
# First check pk Whether there is , If it doesn't exist, it will be reported 404 error
user = get_object_or_404(User, pk=pk)
if request.method == 'POST':
try:
data = request.POST.dict()
User.objects.filter(pk=pk).update(**data)
msg = {'code':0, 'result':' Successfully updated user '}
except:
msg = {'code':1, 'result':' User update failed : '.format(traceback.format_exc())}
return render(request, 'hello/edituser.html', {'user':user, 'msg':msg})

View template configuration

templates\hello\edituser.html

<!-- Inherit the master -->
{% extends "base.html" %}
<!-- rewrite title The content of -->
{% block title %} Update user {% endblock %}
<!-- rewrite body The content of -->
{% block body %}
<!-- Show success or failure information -->
{% if msg.code == 0 %}
<p style="color: green"> {{ msg.result }}</p>
{% else %}
<p style="color: red"> {{ msg.result }}</p>
{% endif %}
<div class="container">
<h2 style="color: #666666"> Update user information </h2><br>
<form method="post" action="">
user name :
<input type="text" name="username" value="{{ user.username }}">
<br>
<br>
password :
<input type="password" name="password" value="{{ user.password }}">
<br>
<br>
Phone number :
<input type="text" name="phone" value="{{ user.phone }}">
<br>
<br>
Gender :
{% if user.sex == 0 %}
<input type="radio" name="sex" value="0" checked> male
<input type="radio" name="sex" value="1"> Woman
{% else %}
<input type="radio" name="sex" value="0" > male
<input type="radio" name="sex" value="0" checked> Woman
{% endif %}
<br>
<br>
<button type="submit"> Submit </button>
<button> <a href="{% url 'hello:showuser' %}"> Cancel </a></button>
</form>
</div>
{% endblock%}

The effect of the front-end display is as follows :

The action item in the user list , Click on to update , Jump to the page :

Modify the user , It's shown as follows :

Put the user name test006 The sex of the female is changed to male , give the result as follows :

When pk When it doesn't exist , The test results are as follows :

Background database look-up table verification under :

2.8 User deletion

Background execution script configuration

hello\view.py

# New code , User delete function
def deluser(request, **kwargs):
msg = {}
pk = kwargs.get('pk', '')
try:
# Gets individual user information
user = User.objects.get(pk=pk)
except User.DoesNotExist:
# If the user doesn't exist , Then return to 404 error
raise Http404
if request.method == 'POST':
try:
User.objects.get(pk=pk).delete()
msg = {'code':0, 'result':' Successfully deleted user '}
except:
msg = {'code': 1, 'result': ' User deletion failed : '.format(traceback.format_exc())}
return render(request, 'hello/deluser.html', {'user':user, 'msg':msg})

View template configuration

templates\hello\deluser.html

<!-- Inherit the master -->
{% extends "base.html" %}
<!-- rewrite title The content of -->
{% block title %} Delete user information {% endblock %}
<!-- rewrite body The content of -->
{% block body %}
<!-- Show success or failure information -->
{% if msg.code == 0 %}
<p style="color: green"> {{ msg.result }} {{ user.username }} </p>
{% else %}
<p style="color: red"> {{ msg.result }}</p>
{% endif %}
<div class="container">
<h2 style="color: #666666"> Delete user information </h2>
<h1 style="color: red"> Are you sure to delete {{ user.username }}? </h1>
<form method="post" action="">
<button type="submit"> determine </button>
<button> <a href="{% url 'hello:showuser' %}"> Cancel </a></button>
</form>
</div>
{% endblock%}

Delete user , It's shown as follows :

The action item in the user list , Click on Delete , Click ok , Successfully returned `:

The effect of deletion failure is as follows :

thus , A simple user system has been completed , Doesn't it look very simple , Let's practice with it , There is a problem , Please feel free to discuss , thank you .

If you think this article is good , Please like it or share it with friends !

If I like my article , Welcome to my official account. : A little bit of technology , Sweep yards attention , Share... From time to time

 official account : A little bit of technology

版权声明
本文为[Single.]所创,转载请带上原文链接,感谢

  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