4. Use django2.0 for development. Background Member Management (2) Use of modelform and data verification

Source: Internet
Author: User
We have finished using modeladmin in the previous section, but we also found that when adding and editing members, we cannot verify whether the data is correct, for example

  1. The username, mobile phone number, and email address must be unique.
  2. User name and password length Verification
  3. If you do not enter a password when editing user information, the password is not updated. If you do, the password is updated.
  4. Text that fails custom Verification
    ...

To meet these requirements, we must use a custom form.

Project address: https://gitee.com/ccnv07/django_example

Introduction to form

Through the form, we can implement the following functions

  1. Custom Field Style
  2. Similar forms can reduce the amount of code through class inheritance
  3. Complete custom form data verification
Define form fields

The form code is usually stored in forms. py of each module.

Description of form field types

Charfield
Single-line text input field, corresponding to the charfield field of the Model
The style in the form is input type = text
max_length: Maximum length
min_length: Minimum Length
strip: Whether to filter left and right Spaces
empty_value: The value when it is null. The default value is a null string.

Emailfield
Enter the text field in the email address, which corresponds to the emailfield field of the model.
Input type = text
However, an email format validation is automatically added.

Choicefield
Drop-down single-choice field, which is not in the Model
Select tag corresponding to the form
choicesParameters are also in the format of two-dimensional tuples.

Booleanfield
Select fields, corresponding to the checkbox in the form

Datefield
Date selection Field
input_formats: Defines the time format. The default value is:

[‘%Y-%m-%d‘,      # ‘2006-10-25‘ ‘%m/%d/%Y‘,      # ‘10/25/2006‘ ‘%m/%d/%y‘]      # ‘10/25/06‘

Datetimefield
Date and Time Field, same as datefield

Timefield
Time Field, same as datefield

Decimalfield
Decimal digit Field
max_value: Maximum Value
min_value: Minimum value
max_digits: The maximum number of digits after the front 0 is removed
decimal_places: Length of allowed decimal places

Filefield
File upload field

Integerfield
Integer field
max_value: Maximum Value
min_value: Minimum value

There are still a lot of form field types, which will be further introduced in subsequent tutorials. Currently, these are even more common fields.

After the introduction, we found that I did not mention the most common passwordfield. In fact, this field type does not exist in Django forms. How can I implement the password field?

Password = forms. charfield (widget = forms. passwordinput (), max_length = 12, min_length = 6, strip = true, help_text = 'Leave the password blank when editing ')

You can set the widget parameter to forms. passwordinput () to implement the password field.

Therefore, it is not the form class that specifies the type of form fields, but the type of form fields implemented by Widgets. For each form field type, Django has a corresponding template, generate the corresponding HTML code through the field parameters

Common Parameters of form fields

label: Name of the label of the form field
widget: Specifies the field style type used for this field
help_text: Field help text

Form meta Meta

Only modelform has metadata. form does not need metadata.
The following is an example of a metabase.

From Django. forms import modelformclass meta: Model = Account # when using a custom form, you must specify the fields or exclude attribute. Otherwise, fields = ('account', 'Password', 'email ', 'phone', 'status') error_messages = {non_field_errors: {'unique _ together ': "% (model_name) S's % (field_labels) s are not unique. ",}}

model: Model bound to modelform
fields: Specify the fields to be displayed when editing is added in the background.
error_messages: Specify common error message text

Other complex operations will be detailed in subsequent tutorials. Now we have completed a form.

Bind the form to modeladmin

However, if you want the form to take effect in the background, you need to bind the form to modeladmin.

from django.contrib import adminfrom .forms import AccountForm@admin.register(Account)class AccountAdmin(admin.ModelAdmin):    form = AccountForm

Specify the form parameter in modeladmin to bind the form. Click the Add/Edit page to see that the form takes effect.

Form data verification

Next, we need to complete the verification method after the form submits data.
In fact, when defining form fields, we have completed part of the verification.
For example

Account = forms. charfield (required = true, error_messages = {'requestred': 'Enter the Username ',}, label = 'username ')

This defines that the account field must be filled in. If an error occurs, the "enter user name" prompt is returned.

However, this does not allow us to complete all our verification, so we can also perform custom Verification Based on the field.
For example, the account username field must be unique.

From Django import formsfrom Django. core. exceptions import validationerrorfrom. models import accountclass accountform (forms. modelform ):... the Code def clean_account (Self) is omitted: _ INFO = account. objects. filter (account = self. cleaned_data ['account'], is_deleted = 0 ). values ('id') If _ INFO: Raise validationerror ('user already exist') return self. cleaned_data ['account']

When we execute Form. when the is_valid () method is used for verification, the Django form class will execute the clean _ field name custom verification method in sequence. if an exception is thrown (raise validationerror ('user already exist ')), the command is interrupted and an error is returned. Otherwise, the return value of the clean _ field name method is read and written to the cleaned_data dictionary.

Based on the same method, we can also write verification for the email and phone fields.

Operate form in modeladmin

The above functions can be basically implemented, but in the background operations, the same form is added and edited. If we need to add and edit different scenarios, it is quite troublesome to perform different operations.
Therefore, we need to perform certain operations on the form in modeladmin. Similar forms can complete more judgments.

# Account/admin. pyclass accountadmin (Admin. modeladmin): def get_form (self, request, OBJ = none, ** kwargs): form = super (accountadmin, self ). get_form (request, OBJ = OBJ, ** kwargs) # OBJ stores models. account Information # assign the form to different scenarios based on the existence of PK, and perform different verification based on different scenarios if (obj is not none): form. id = obj. PK form. scene = 'update' else: form. scene = 'insert' return form

Parameters of the get_form MethodrequestThe httprequest operation object is saved.
OBJ is the data model object of the current operation, and obj is none in the new operation. OBJ exists only during editing.

form = super(AccountAdmin, self).get_form(request, obj=obj, **kwargs)Returns the form object of the current operation.
If obj is not none, the current operation is edited. we can add a custom attribute scene (scenario) = 'update' to the form. Otherwise, the object is added.

In addition, we can perform different verification and judgment for different scenarios in form.

# Account/forms. pyclass accountform (forms. modelform): def clean_account (Self): # automatically verify the account field if self. scene = 'insert': _ INFO = account. objects. filter (account = self. cleaned_data ['account'], is_deleted = 0 ). values ('id') Elif self. scene = 'update': _ INFO = account. objects. filter (~ Q (ID = self. ID) & Q (account = self. cleaned_data ['account']) & Q (is_deleted = 0 )). values ('id') If _ INFO: Raise validationerror ('user already exist') return self. cleaned_data ['account']

This verification means that if the current scenario (self. Scene) is insert, it will only query by account. If it is update, it will add a filter condition where the ID is not the ID of the current operation.

Django's password encryption method

Django. contrib. Auth. hashers has two methods for password encryption.
Make_password and check_password

Make_password is used to encrypt the specified plaintext password.
Check_password is used to verify whether the plaintext password given is correct.

Add and edit different operations in the password box

When a user is added, the password box is required. When editing, the password box is not required. If yes, change the password. If no, do not change the password.

Step 1: When verifying the entered password, we also need to encrypt the password (after all, the database is cracked and the background is still very serious)

From Django import formsclass accountform (forms. modelform): def clean_password (Self): # automatically verify the password field if self. scene = 'insert': If not self. cleaned_data ['Password']: Raise validationerror ('Enter the password') Elif self. scene = 'update': If not self. cleaned_data ['Password']: Return none else: return self. cleaned_data ['Password'] Return make_password (self. cleaned_data ['Password'])

This is also easy to understand. If no password is entered when a new user is added, an error is returned.
If no password is entered during the update, none is returned.
If entered, the password string encrypted by make_password is returned.

This function can be easily implemented based on the scene scenario parameter specified in the previous tutorial. However, if the password is left blank during editing, It will be set to null.

This is because if you do not enter the password, the model object will always carry Password = none. When you convert it to SQL Execution, it will become Password = ''.

Therefore, if there is no input value for the password, we need to destroy the password carried by the model before saving it.

Override the Save method of modeladmin

class AccountAdmin(admin.ModelAdmin):    def save_model(self, request, obj, form, change):        if form.cleaned_data[‘password‘] is None:            del obj.password        super().save_model(request, obj, form, change)

Form. cleaned_data indicates the data that has been verified after the form is submitted. If the password is none, del the data. Then, call the save_model method of the parent class to continue the save operation.

4. Use django2.0 for development. Background Member Management (2) Use of modelform and data verification

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.