Home  >  Article  >  Backend Development  >  Introduction to the ModelForm component in Django (code example)

Introduction to the ModelForm component in Django (code example)

不言
不言forward
2019-03-13 13:23:172355browse

This article brings you an introduction to the ModelForm component in Django (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. help.

Usually in Django projects, most of what we write are forms that closely map to Django's models. For example, you might have a Book model, and you want to create a form to add and edit book information to the model. In this case, defining fields in the form will be redundant since we have already defined those fields in the model.

For this reason, Django provides an auxiliary class that allows us to create a Form from Django's model, which is ModelForm.

modelForm definition

The combination of form and model.

from django import forms
from crm import models

class RegForm(forms.ModelForm):
    password = forms.CharField(
        widget=forms.PasswordInput,
        label='密码',
        min_length=6,
        max_length=12
    )
    re_password = forms.CharField(
        widget=forms.PasswordInput,
        label='确认密码',
        min_length=6,
        max_length=12
    )
    mobile = forms.CharField(

    )
    class Meta:
        model = models.UserProfile  # 指定model
        fields = '__all__'  # 全部字段
        # fields = ['username','password']  # 指定字段
        exclude = ['is_active']  # 除某个字段之外的其余字段
        labels = {
            'username':'用户名'
        }
        error_messages = {
            'min_length': '太短了',
        }
        widgets = {
            'username': forms.TextInput(attrs={'placeholder': '用户名@xx.com'}),
        }

class Commonly used parameters under Meta:

model = models.Book  # 对应的Model中的类
fields = "__all__"  # 字段,如果是__all__,就是表示列出所有的字段
exclude = None  # 排除的字段
labels = None  # 提示信息
help_texts = None  # 帮助提示信息
widgets = None  # 自定义插件
error_messages = None  # 自定义错误信息

ModelForm validation

Similar to the ordinary Form form validation type, ModelForm form validation requires calling is_valid() or accessing errors Called implicitly when using a property.

We can customize local hook methods and global hook methods to implement custom verification rules just like using the Form class.

If we do not rewrite specific fields and set the validators attribute, ModelForm is verified according to the validators of the fields in the model.

save() method

Each ModelForm also has a save() method. This method creates and saves a database object based on the data bound to the form. Subclasses of ModelForm can accept an existing model instance as the keyword argument instance; if this functionality is provided, save() will update the instance. If not provided, save() will create a new instance of the model:

>>> from myapp.models import Book
>>> from myapp.forms import BookForm

# 根据POST数据创建一个新的form对象
>>> form_obj = BookForm(request.POST)

# 创建书籍对象
>>> new_ book = form_obj.save()

# 基于一个书籍对象创建form对象
>>> edit_obj = Book.objects.get(id=1)
# 使用POST提交的数据更新书籍对象
>>> form_obj = BookForm(request.POST, instance=edit_obj)
>>> form_obj.save()

The above is the detailed content of Introduction to the ModelForm component in Django (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete