[toc]
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