1. Build a form
View file:
from django.shortcuts import render
# Create your views here.
def getdata(request):
data = ''
# number = 0
if 'data' in request.POST:
# 获取客户端提交data
data = request.POST['data']
number = data * 2
return render(request,'index.html',{"current_data":data,"number":number})
Subroutes:
from django.urls import path
from app import views
urlpatterns = [
path('getdata/',views.getdata),
]
Template file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- 注意此时的getdata两边需要斜杆,同时它是指连接路由名叫getdata的路由 -->
<from action="/getdata/" method="POST">
{% csrf_token %}
<label for="data">请输入数据:</label>
<input id="data" type="text" name="data" value="{
{current_data}}">
<input type="submit" value="提交">
<p>计算得到的结果是:{
{number}}</p>
</from>
</body>
</html>
2. Detailed explanation of Django form classes
- The custom form class dataForm inherits the django.forms.Form class and contains a data field.
- The type of field data is forms.CharField. The form data field will be rendered as a <label> element and an <input> element
- The label parameter of the form field specifies the string displayed in the <label> element generated by form rendering.
1. Detailed explanation of fields
Common form field classes
- The bound form has submitted data, so it can be used to determine whether the data is legal.
is_bound
The properties of the form are used to determine whether there is bound data. - label_suffix: The label_suffix attribute is used to set the suffix of the text content when the form field is rendered as an HTML <label> element. The default suffix is an English colon ":"
- The help_text parameter is used to set the help information of the field. The help information is rendered as a <span> element.
- error_messages is used to set custom error messages, which will override the default error messages.
- The parameter value of error_messages is a dictionary object, each key-value pair corresponds to a verification error message
- When the disabled parameter is set to True, the HTML elements rendered into form fields are not allowed to interact with the user.
>>> class test(forms.Form):
... addr=forms.CharField(label='联系地址',label_suffix='*')
...
>>> print(test())
class test(forms.Form):
... addr=forms.CharField(label='联系地址',disabled=True)
...
>>> print(test())
#initial参数用于设置字段的初始值
>>> class test(forms.Form):
... name=forms.CharField(initial='someone')
...
>>> print(test(auto_id=False))
#也可在创建表单对象时提供初始值:
>>> d=test({'name':'Lining'},auto_id=False)
>>> print(d)
from django import forms
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField(widget=forms.Textarea)
sender = forms.EmailField()
cc_myself = forms.BooleanField(required=False)
class dataForm2(forms.Form):
data = forms.CharField(label='请输入数据:')
a = forms.BooleanField(label='a')
sex = forms.ChoiceField(label='sex')
date = forms.DateField(label='date')
def useDataForm2(request):
return render(request,'form2.html',{'form':dataForm2()})
form2 view:
2.Controls
Each form field has a control class, and the control class corresponds to the HTML form control. For example: <input type="text">
each form field has a default control. For example, the default control of charfield is TextInput
. If you want to specify the control as follows:
from django import forms
class RunApiForm(forms.Form):
query_params = forms.CharField(label='查询参数', required=False, widget=forms.Textarea(attrs={'rows': 6,'cols': 80,}))
from django import forms
class dataForm(forms.Form):
data = forms.CharField(label="请输入数据")
3. Use django form template
1 Form rendering options
{ { form.as_table }}
Render them as table cells contained in labels{ { form.as_p }}
wrap them in<p>
tags{ { form.as_ul }}
wrap them in<li>
tags
View file:
from django import forms
class dataForm(forms.Form):
data = forms.CharField(label="请输入数据")
def useDataForm1(request):
if request.method == 'POST':
form = dataForm(request.POST)
msg = '已完成数据提交'
else:
# 创建空表单
form = dataForm()
msg = '初始化表单'
return render(request,'data1.html',{'form':form,'msg':msg})
data1.html file:
<form action="/your-name/" method="post">
{% csrf_token %}
{
{ form }}
<input type="submit" value="Submit">
</form>
<form action="/your-name/" method="post">
{% csrf_token %}
{
{ form.as_table }}
<input type="submit" value="Submit">
</form>
<form action="/your-name/" method="post">
{% csrf_token %}
{
{ form.as_p }}
<input type="submit" value="Submit">
</form>
<form action="/your-name/" method="post">
{% csrf_token %}
{
{ form.as_table }}
<input type="submit" value="Submit">
</form>
2 Manually rendering fields(ing)
{
{fom.fieldname.lable}}: The label text of the field, for example, "name".
{
{fom.Field name.lable_tag}}: The label text encapsulated in the HTML-label element, including the label_suffix of the form.
{
{form.fieldname.value}}: field value.
{
{form.fieldname.help_text}}: Help text of the field.
{
{form.fieldname.errors}}: Error message when the field fails validation.
{
{fom.Field name.field}};: BoundField instance object of the form field, used to access field properties. For example, {
{form.name.field.max_length}}.
View file:
from django import forms
class test(forms.Form):
name = forms.CharField(max_length=50,label='姓名')
age = forms.IntegerField(max_value=50,min_value=15,label='年龄',help_text='年龄大于15且小于50')
def useTest(request):
if request.method == 'POST':
form = test(request.POST)
else:
form = test()
return render(request,'tem.html',{"form":form})
tem.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="/diy/",method='POST'>
{% csrf_token %}
<div>
{
{form.name.label}}:{
{form.name}}
</div>
<div>
{
{form.age.label}}:{
{form.age}}{
{form.age.help_text}}
</div>
<input type="submit" value="提交">
</form>
</body>
</html>
3 Traverse form fields
View file:
# 遍历字段
class test1(forms.Form):
name = forms.CharField(max_length=50,label='姓名')
age = forms.IntegerField(max_value=50,min_value=15,label='年龄',help_text='年龄大于15且小于50')
def useTe(request):
if request.method == 'POST':
form = test1(request.POST)
else:
form = test1()
return render(request,'bianli.html',{"form":form})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h3>遍历表单字段</h3>
<form action="/diyfor/" method="POST">
{% csrf_token %}
{% for field in form %}
<p>
{
{ field.errors }}
//这个是标签中的固定值:例如:姓名,年龄
<b>{
{ field.label_tag }}</b>
{
{ field }}
{% if field.help_text %}
<I>{
{ field.help_text|safe }}</I>
{% endif %}
</p>
{% endfor %}
<input type="submit" value="提交">
</form>
</body>
</html>
4. Form set
View file:
from django.forms import formset_factory
def useform(request):
classTestForm = formset_factory(test,extra=2)
if request.method == 'POST':
formset = classTestForm(request.POST)
else:
formset = classTestForm()
return render(request,'temform.html',{'formset':formset})
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="/formset/" method="POST">
{% csrf_token %}
<table>
{
{ formset }}
</table>
<input type="submit" value="提交">
</form>
</body>
</html>
5. Model form
Note: Need to connect to database
model.py
from django.db import models
# Create your models here.
class person(models.Model):
name = models.CharField(max_length=8)
age = models.SmallIntegerField()
View file:
from .models import person
from django.forms import ModelForm
class personForm(ModelForm):
class Meta:
model = person
fields = '__all__'
def usePersonForm(request):
# 在提交表单时采用post
if request.method == 'POST':
# 初始化表单
mform = personForm(request.POST)
# 在表单通过验证时执行数据处理
if mform.is_valid():
# 用表单数据查询
ps = person.objects.filter(name=request.POST['name'])
if ps.count() == 0:
mform.save()
msg = '数据已保存'
else:
msg = '数据库已存在相同姓名的数据,请勿重复提交'
else:
msg = '表单数据有错'
else:
# 创建空白表单
mform = personForm()
msg = '请输入数据添加新纪录'
return render(request,'moxing.html',{'mform':mform,'msg':msg})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="/mform/" method="POST">
{% csrf_token %}
<table>
{
{mform}}
</table>
<input type="submit" value="提交">
</form>
<hr/>
{
{msg}}
</body>
</html>
View file:
class personFormDIY(ModelForm):
age = forms.CharField(validators=[validata_age],label='年龄',\
widget = forms.NumberInput(),\
help_text='年龄为[20,50]以内的整数')
class Meta:
model = person
fields = ['name','age']
labels = {'name':'姓名',}
help_texts = {'name':'姓名为中文英文字符串',}
widgets = {'name':forms.Textarea(attrs={'cols':30,'rows':2}),}
def usePersonFormDIY(request):
# 在提交表单时采用post
if request.method == 'POST':
# 初始化表单
mform = personForm(request.POST)
# 在表单通过验证时执行数据处理
if mform.is_valid():
# 用表单数据查询
ps = person.objects.filter(name=request.POST['name'])
if ps.count() == 0:
mform.save()
msg = '数据已保存'
else:
msg = '数据库已存在相同姓名的数据,请勿重复提交'
else:
msg = '表单数据有错'
else:
# 创建空白表单
mform = personForm()
msg = '请输入数据添加新纪录'
return render(request,'moxing.html',{'mform':mform,'msg':msg})
6.admin site
1. Create a super administrator
Note: You need to migrate the database to open the page
python manage.py createsuperuser
The database can be changed using the file form:
from django.contrib.auth.models import User
user = User.objects.create(username='admin')
user.set_password('123456')
user.is_superuser=True
user.save()
2. Change the admin site language
change to:
You can also change the following method to change the language (both methods are acceptable)
Add this line:
3.Model management
Note: This operation requires database migration
admin.py:
from django.contrib import admin
# Register your models here.
from .models import bookinfo
#网站的url标题
admin.site.site_title='在线图书馆后台管理系统'
#网站标题
admin.site.site_header='在线管理网站'
#注册模型
admin.site.register(bookinfo)
models.py:
from django.db import models
# Create your models here.
class bookinfo(models.Model):
name = models.CharField(max_length=20,verbose_name='书籍名')
author = models.CharField(max_length=20,verbose_name='书籍作者')
price = models.IntegerField(verbose_name='书籍定价')
class Meta:
verbose_name = '书籍信息'
verbose_name_plural = '书籍信息'
Change app name:
__init__.py:
default_app_config = 'app.apps.AppConfig'
apps.py:
from django.apps import AppConfig
class AppConfig(AppConfig):
name = 'app'
verbose_name = '图书信息系统'
4. List page options
admin.py:
from django.contrib import admin
# Register your models here.
from .models import bookinfo
admin.site.site_title='在线图书馆后台管理系统'
admin.site.site_header='在线管理网站'
# admin.site.register(bookinfo)
@admin.register(bookinfo)
class Bookadmin(admin.ModelAdmin):
# 需要展示的信息
list_display = ('id','name','author','price')
# 点击之后可以以链接的形式展示
list_display_links = ('id','name')
# 右边显示的过滤器
list_filter = ('name',)
# 显示搜索的信息,搜索框
search_fields = ('author','name')
# 排序
ordering = ('price',)
# 类似于分页,需要显示的条数
list_per_page = 1
# 表示其他的可以更改,但是名字不可以更改
readonly_fields = ('name',)
# 表示可以更改价格
list_editable = ('price',)
5. Custom download editing
admin.py
from django.contrib import admin
# Register your models here.
from .models import bookinfo
admin.site.site_title='在线图书馆后台管理系统'
admin.site.site_header='在线管理网站'
# admin.site.register(bookinfo)
from django.http import HttpResponse
from django.utils.encoding import escape_uri_path
from openpyxl import Workbook
@admin.register(bookinfo)
class Bookadmin(admin.ModelAdmin):
def download_excel(self,request,queryset):
file_name = '书籍信息.xlsx'
# 用于定义文件名,格式为:app名.模型名
meta = self.model._meta
# 模型所有字段名
field_names = [field.name for field in meta.fields]
# 定义响应数据格式
response = HttpResponse(content_type='application/msexcel')
response['Content-Disposition'] = "attachment;filename*=utf-8'{}".format(escape_uri_path(file_name))
# 新建workbook
wb = Workbook()
# 使用当前活动的sheet表
ws= wb.active
ws.append(['ID','书籍名称','作者','书籍定价'])
for obj in queryset:
for field in field_names:
data = [getattr(obj,field) for field in field_names]
ws.append(data)
wb.save(response)
return response
download_excel.short_description = '下载书籍信息'
# 需要展示的信息
list_display = ('id','name','author','price')
# 点击之后可以以链接的形式展示
list_display_links = ('id','name')
# 右边显示的过滤器
list_filter = ('name',)
# 显示搜索的信息,搜索框
search_fields = ('author','name')
# 排序
ordering = ('price',)
# 类似于分页,需要显示的条数
list_per_page = 1
# 表示其他的可以更改,但是名字不可以更改
readonly_fields = ('name',)
# 表示可以更改价格
list_editable = ('price',)
actions = (download_excel,)
actions_on_top = False
actions_on_bottom = True
6. Edit page options
admin.py
# 控制编辑页面需要显示的字段
fields = (('name','author'),('price',))
# 对编辑字段进行分组
fieldsets = (('书籍基本信息',{'fields':['name','author']}),
('书籍价格信息',{'fields':['price']}))
# 表示只读字段
readonly_fields = ('name',)
7. Optimize the page
pip install django-simpleui
pip list
STATIC_DIRS = [os.path.join(BASE_DIR,'static')]
STATIC_ROOT = os.path.join(BASE_DIR,'/static/')
python manage.py collectstatic
//将admin文件复制到项目文件static目录下
python manage.py runserver
8. User authentication
Create a normal user:
from django.contrib.auth.models import User
user = User.objects.create(username='testuser')
user.set_password('123456')
user.save()
Create superuser:
user = User.objects.create_superuser('admin3', '[email protected]', '123456')
Modify object:
user = User.objects.get(username='testuser')
user.email
user.email = '[email protected]'
user.save()
user.email
#'[email protected]'
Delete object:
user = User.objects.get(username='test')
user.delete()
#(4, {'admin.LogEntry': 0, 'auth.User_groups': 1, 'auth.User_user_permissions': 2, 'auth.User': 1})
Verify user:
from django.contrib.auth import authenticate
user = authenticate(username='testuser',password='123456')
print(user)
#testuser
user = authenticate(username='testuser',password='456')
print(user)
#None
Setting permissions:
from django.contrib.auth.models import Permission
from django.contrib.auth import get_user_model
User = get_user_model()
admin_permissions = Permission.objects.filter(codename__endswith='permission')
user = User.objects.get(username='testuser')
user.user_permissions.set(admin_permissions)
for p in user.user_permission.all():
print(p.codename.p.name)
from app.models import bookinfo
from django.contrib.contenttypes.models import ContentType
content_type_id = ContentType.objects.get_for_model(bookinfo)
p = Permission.objects.create(codename='can_analyse_person',name='能分析person数据',con
tent_type=content_type_id)
user.user_permissions.add(p)
View the visualization page:
from django.contrib.auth.models import Permission
from django.contrib.auth.models import User
p = Permission.objects.get(codename='view_permission')
user = User.objects.get(username='testuser')
p.user_set.add(user)
p.user_set.all()
#<QuerySet [<User: testuser>]>
from django.contrib.auth.models import Group
g = Group.objects.get(id = 1)
g.user_set.add(user)