Django --- many relationships created, forms component

Three ways to create many-ways

1. Create a system of direct

When you create a table of the system to create a third table,

advantage:

1. The system can be used carrying CRUD

2. no longer need to manually create the table

Disadvantages:

1. Create a table out of no way to make changes, scalability bad

authers = models.ManyToManyField(to='Auther')

2. Manually create your own

You can create a third table according to their needs, create a table when the best time-to-many relationship, the data in the table were constrained to ensure the reliability of the data.

advantage:

1. Create a table out can be modified in accordance with their use

2. high scalability

Disadvantages:

1. There is no way to use multi-table operation, you can use many, one way to be modified

2. does not support cross-table query

class AutherBook(models.Model):
    auther = models.ForeignKey(to='Auther') 
    book = models.ForeignKey(to='Book')

3. create and add their own definition system

Define yourself a table, then the system-defined table points to set their own table.

advantage:

1. You can modify fields in the table

2. support cross-table query

Disadvantages:

1. does not support multi-table operations

authers = models.ManyToManyField(to='Auther',through='AutherBook',through_fields=('book','authers'))

# through  指定自己创建的第三张表
# theough_fields   指定第三张表中与之关联的字段,有顺序要求,定义的外键字段在谁那里,就先写谁

forms component

The main function of forms components:

1. available HTML tags may be generated

2. The data submitted by the user to be verified

3. Keep last Input content

forms component can be above these three things better complete.

1. How to use the forms component

The forms need to use django module

from django import forms
# 首先需要提前写一个类用来继承Form类,然后就可以通过这个类来
class MyForm(forms.Form):
    # username字段 最少三位 最多八位
    username = forms.CharField(max_length=8,min_length=3)
    # password字段 最少三位  最多八位
    password = forms.CharField(max_length=8,min_length=3)
    # email字段 必须是邮箱格式
    email = forms.EmailField()

2. check data forms assembly

  1. Written to the class, the dictionary data transfer (data to be verified) instantiates an object is to be calibrated;
  2. obj.is_valid () to view the check data is legitimate;
  3. obj.errors see the field and for the wrong reasons does not comply with the rules;
  4. obj.cleaned_data view the data in line with validation rules;

note!

  1. When using the assembly forms, written field default class is defined to be passed by value can not be less mass.
  2. forms assembly forms only check field defined in the class. If you multi-pass, and will not have any effect.

3. Use the forms to render the component label

Features:

forms will help you render the component label get user input, will not help you render the submit button, you need to manually add.

Rendering label mode 1:

{{ form_obj.as_p }}  // 里面所有标签都有

2 :( way to render the label is not recommended, write up more trouble, each row must write your own)

{{ form_obj.username.label }}{{ form_obj.username }}  // 只有username一个标签

Rendering label recommended way :( 3, when I remember to use plus the submit button)

{% for form in form_obj %}
    <p>{{ form.label }}{{ form }}</p>  <!--form 等价于你方式2中的对象点字段名-->
{% endfor %}

Changing the label to show the rendering of characters: Add a label to the property field, displayed at the time shows the label corresponding Chinese name

class MyForm(forms.Form):
    username = forms.CharField(max_length=8,min_length=3,label='用户名')
    password = forms.CharField(max_length=8,min_length=3,label='密码')
    email = forms.EmailField(label='邮箱')

4. Information display assembly forms

<form action="" method="post" novalidate>
    {% for forms in form_obj %}
    <p>
        {{ forms.label }}{{ forms }}
        <span>{{ forms.errors.0 }}</span>
        error里面正好是一个一个标签对应的报错信息列表
        .0 可以拿到里面的一个一个文本,
        这样既可以随便在哪个位置展示了
    </p>  <!--form 等价于你方式2中的对象点字段名-->
    {% endfor %}
    <input type="submit">
</form>

The front end of the check data is prohibited parameters

Front and rear ends calibration data generally must have.

However, the front end of the check dispensable,

Back-end verification must have! And we must be very comprehensive!

How to tell the browser front-end do not check:

form表单中加一个novalidate参数即可
<form action="" method="post" novalidate>

5.1 Error Messages modifications: error_messages

Front page can modify the displayed error message, each piece of data may correspond to modifications.

username = forms.CharField(
    max_length=8,
    min_length=3,
    label='用户名',
    initial='默认值',
    error_messages={
        'max_length':'用户名最长八位',
        'min_length':'用户名最短三位',
        'required':'用户名不能为空'
    },
)

email = forms.EmailField(
    label='邮箱',
    error_messages={
        'required':'邮箱不能为空',
        'invalid':'邮箱格式错误'  # 这条显示邮箱格式错误的报错信息
    }
)

5.2 Regular checker: RegexValidator

By regular check data format matches

# 需要先导入RegexValidator模块
from django.core.validators import RegexValidator
validators=[
    RegexValidator(r'^[0-9]+$', '请输入数字'),
    RegexValidator(r'^159[0-9]+$', '数字必须以159开头'),
]

5.3 set the style and property to the input box: widget

You can be modified with a label widget class attribute or style css

  1. 密码password:widget=forms.widgets.PasswordInput()
  2. 单选radioSelect:widget=forms.widgets.RadioSelect()
  3. 多选Select:widget=forms.widgets.SelectMultiple()
  4. 单选checkbox:widget=forms.widgets.CheckboxInput()
  5. 多选checkbox:widget=forms.widgets.CheckboxSelectMultiple()
password = forms.CharField(
        min_length=6,
        label="密码",
        widget=forms.widgets.PasswordInput(  ###
            attrs={'class': 'c1'}, 
            render_value=True
        )
)

5.4 input box defaults: initial

gender = forms.fields.ChoiceField(
        choices=((1, "男"), (2, "女"), (3, "保密")),
        label="性别",
        initial=3,  ###
        widget=forms.widgets.RadioSelect()
    )

5.5 Control field Required: required

email = forms.EmailField(
    label='邮箱',
    error_messages={
        'required':'邮箱不能为空',  ### 默认为True,可以为空
        'invalid':'邮箱格式错误'
    }
)

5.6 input corresponding message: label

Can point label tags checkbox is selected

gender = forms.fields.ChoiceField(
        choices=((1, "男"), (2, "女"), (3, "保密")),
        label="性别",  
        initial=3,  
        widget=forms.widgets.RadioSelect()
    )

6. hook function

At a particular time, crawl specific content.

Hook function is a function, the function body you can write any check code.

He called automatically executed after data validation by.

6.1 partial hook

Function named clean_单个字段名, will be prompted at the time of writing

# 校验用户名中不能含有666
def clean_username(self):
    username = self.cleaned_data.get('username')
    if '666' in username:
        # 给username所对应的框展示错误信息
        self.add_error('username','光喊666是不行的')
        # raise ValidationError('到底对不对啊')
    # 将单个数据username数据返回
    return username

6.2 Global hook

Function named clean, all keys will cleaned_data in a one for verification. .

def clean(self):
    password = self.cleaned_data.get("password")
    confirm_password = self.cleaned_data.get("confirm_password")
    if not password == confirm_password:
        self.add_error('confirm_password','两次密码不一致')
    # 将全局的数据返回
    return self.cleaned_data

Guess you like

Origin www.cnblogs.com/whkzm/p/11980639.html