current position:Home>Django - (7)

Django - (7)

2022-09-09 06:48:54AL_QX

内容概览

  • 批量操作数据
  • Bulk data display
  • form组件
  • modelform组件

批量操作数据

"""Implements browser access to onedjango路由,立刻创建10Thousands of data and display"""
def func(request):
	for i in range(100000):
		models.Book.objects.create(title=f'第{
      i}本书')  # Create 100,000 pieces of data in the database
	book_obj = modles.Book.objects.all()
	return render(request, 'bookList.html', locals())
"""When it comes to the creation of large batches of data,直接使用createCreation may crash the database,So another method needs to be used"""
	book_list=[]
	for i in range(100000):
		book_obj = models.Book(title=f'第{
      i}本书')  # Create book objects in a loop
		book_list.append(book_obj)  # Add the book object to the list
	models.Book.objects.bulk_create(book_list)  # 批量创建数据
	book_query = models.Book.objects.all()
	return render(request, 'bookList.html', locals())
	"""也可以使用bulk_update()批量修改数据"""

Bulk data display

"""When the amount of data to be displayed is relatively large,Pages should take into account pagination handling"""
1. Slice the data first,Limit the number of impressions per page
	book_obj = models.Book.objects.all()
	current_page = request.GET.get('page', 1)  # 当前页数,默认为1
    try:
        current_page = int(current_page)  # Set to when the current page count is not a number1
    except Exception:
        current_page = 1
    if current_page < 1:  # The current page count is less than1时设置为1
        current_page = 1
    page_show_num = 10  # 每页展示数量
    page_start = (current_page - 1) * page_show_num  # 起始位置
    page_end = page_start + page_show_num  # 结束位置
    book_obj = book_obj[page_start:page_end]  # 切片
    2. 在htmlAdd pagination style to the page
    3. 展示页码
    """使用divmod()方法"""
    book_obj_num = models.BookT.objects.all().count()  # 统计数据个数
    page_num, surplus = divmod(book_obj_num, page_show_num)  # 求出商和余数
    if surplus:  # If there is a remainder, add the number of pages1
        page_num += 1
    page_li_html = ''
    # for i in range(1, page_num + 1): # html页面没有range方法,After writing in the backend, use it in the frontendsafe过滤器
    # page_li_html += f'<li><a href="?page={i}">{i}</a></li>'
    4. Limit the number of page numbers displayed
    xxx = current_page
    if current_page < 6:
        xxx = 6
    for i in range(xxx - 5, xxx + 6):  # 设置显示范围
        if current_page == i:
            page_li_html += '<li class="active"><a href="?page=%s">%s</a></li>' % (i, i)
        else:
            page_li_html += '<li><a href="?page=%s">%s</a></li>' % (i, i)

    return render(request, 'func01.html', locals())

form组件

"""Write the user login function and verify the data to return the prompt information"""
def ab_form(request):
	data_dict = {
    'username': '', 'password': ''}  # 记录报错信息
	if request.method == 'POST':
		username = request.POST.get('username')
		password = request.POST.get('password')
		if username == 'jason':
			data_dict['username'] = '用户已存在'
		if password == '123':
			data_dict['password'] = '密码太简单'
	return render(request, 'ab_form.html', locals())
"""It's too much trouble to write it yourself every time,使用formcomponents can be implemented directly"""

form组件功能

  1. 数据校验:Set various validation rules in advance,then auto-check
  2. 渲染页面:Various tags for obtaining user data can be directly rendered
  3. 展示信息:Support to display different prompts for different verification failures

form类型创建

"""先导入模块"""
from django import forms
class MyForm(forms.Form):
	name = forms.CharField(max_length=8, min_length=2)  # Up to eight characters,Minimum two characters
	age = forms.IntegerField(max_value=150, min_value=0)  # 数字最大为150,最小为0
	email = forms.EmailField()  # 必须符合邮箱格式

数据校验功能

1. Pass the data to be verified
	form_obj = views.MyForm({
    'name': 'jason', 'age': 18, 'email': 123})
2. Determine whether all the data conform to the rules
	form_obj.is_valid()  # False,只要有一个不符合就是False
3. 获取符合校验规则的数据
	form_obj.cleaned_data  # {'name': 'jason', 'age': 18},Only return data that matches the validation rules
4. Get the data that does not meet the validation rules and the reason for the error
	form_obj.errors
	""" <ul class="errorlist"> <li>email <ul class="errorlist"> <li>Enter a valid email address. </li> </ul> </li> </ul> """
""" formIf the fields written in the class are not filled in, it will definitely fail the verification If more fields are passed,Multi-passed fields do not participate in validation """

渲染标签功能

1. 方式1:
{
   { form_obj.as_p }}  <!--使用p标签-->
{
   { form_obj.as_table }}  <!--使用input标签-->
{
   { form_obj.as_ul }}  <!--使用li标签-->
<!--封装程度高,使用方便;但是扩展性差-->
2. 方式2:
{
   { form_obj.name.label }}  <!--nameCapitalize field names-->
{
   { form_obj.name }}  <!--input框-->
<!--封装程度低,扩展性好;But it is difficult to write when there is too much data-->
3. 方式3:
{% for form in form_obj %}
{
   {form.label}}
{
   {form}}
{% endfor %}

The label styles in the class are automatically rendered,The rest of the tags need to be written by yourself

展示提示信息

html:

The browser will automatically add the data validation function,You can set parameters to cancel this function:novalidate
<form action='' method='post' novalidate>
{% for form in form_obj %}
	<p>
		{
   { form.label }}{
   { form }}
		<span style="color: red;">{
   { form.errors.0 }}</span>  <!--errors.0为错误信息-->
	</p>
{% endfor %}
<input type="submit" value="提交">

py:

def func(request):
	form_obj = MyForm()
	if request.method == 'POST':
		form_obj = MyForm(request.POST)  # Pass in the data sent by the front endforms对象做校验
		if form_obj.is_valid():  # If the verification passes, do other operations,If it fails, send an object with error information to the page
			print(form_obj.cleaned_data)
	return render(request, 'func.html', locals())

Important field parameters

max_length/min_length		最多/Minimum number of characters
max_value/min_value			最大/最小数字
label						字段注释,设置前端label显示信息
error_messages				设置错误提示
required					Whether the setting can be empty
widget						The label type can be set/标签属性
initial						初始值
validators					正则校验

钩子函数

Provides custom validation methods,写在Form类里

"""局部钩子:校验单个字段"""
def clean_name(self):
	name = self.cleaned_data.get('name')  # The hook function will be executed after the first layer of verification is completed
        res = models.User.objects.filter(name=name).first()
        if res:
            return self.add_error('name', '用户名已存在')  # Add error message to field
        return name  # The retrieved data needs to be sent back
"""全局钩子:校验多个字段"""
def clean(self):
	pwd = self.cleaned_data.get('pwd')
	confirm_pwd = self.cleaned_data.get('confirm_pwd')  # 在formAdd a field to the class to confirm the password
	if pwd != confirm_pwd:
		return self.add_error('confirm_pwd', '两次密码不一致')
	return self.confirm_data  # Fetching all data requires returning all data

modelform组件

modelform是form的优化版本,使用更加简单,功能也更强大

class MyModelForm(forms.ModelForm):
	class Meta:
		model = models.Book  # 对应models中的类(表)
		fields = "__all__"  # 选择字段,__all__表示所有字段
	def clean_name(self):  # Hooks are also supported,使用方式与form组件相同
		name = self.cleaned_data.get('name')
		res = models.User.objects.filter(name=name).first()
		if res:
			return self.add_error('name', '用户名已存在')
		return name

class Meta下常用参数

model 			对应models中的类
field			字段,__all__代表所有字段
exclude			排除的字段
labels			提示信息
widgets			自定义插件
error_messaes	自定义错误信息

copyright notice
author[AL_QX],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/252/202209090541373683.html

Random recommended