基于model的form表单

Django 提供一个辅助类来让你可以从Django 的模型创建表单。生成的表单类中将具有和指定的模型字段对应的表单字段,顺序为fields 属性中指定的顺序。
 
ForeignKey 和 ManyToManyField 字段类型
ForeignKey 表示成django.forms.ModelChoiceField,它是一个ChoiceField,其选项是模型的查询集。
ManyToManyField 表示成django.forms.ModelMultipleChoiceField,它是一个MultipleChoiceField,其选项是模型的查询集。

生成的每个表单字段都有以下属性集

模型字段设置blank=True,则required=True。
表单字段的label 设置为模型字段的verbose_name,并将第一个字母大写。
表单字段的help_text 设置为模型字段的help_text。
如果模型字段设置了choices,那么表单字段的Widget 将设置成Select,其选项来自模型字段的choices。选项通常会包含空选项,并且会默认选择。如果字段是必选的,它会强制用户选择一个选项。如果模型字段的blank=False 且具有一个显示的default 值,将不会包含空选项(初始将选择default 值)。

示例

model

from django.db import models
TITLE_CHOICES = (
    ('MR', 'Mr.'),
    ('MRS', 'Mrs.'),
    ('MS', 'Ms.'),
)
class Author(models.Model):
    name = models.CharField(max_length=100)
    title = models.CharField(max_length=3, choices=TITLE_CHOICES)
    birth_date = models.DateField(blank=True, null=True)
class Book(models.Model):
    name = models.CharField(max_length=100)
    authors = models.ManyToManyField(Author)

forms.py

from django.forms import ModelForm, Textarea
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ValidationError
from model_form.models import Author
def validate_begins(value):
    """自定义验证器"""
    if not value.startswith(u'new'):
        raise ValidationError(u'字符串必须是 `new` 开头')
class AuthorForm(ModelForm):
    # 使用自定义的字段
    # name = MyFormField(max_length=200, required=False, validators=[validate_slug]
    def __init__(self, *args, **kwargs):
        print("执行顺序1:init")
        # 自定义ModelForm中的field验证规则
        super(AuthorForm, self).__init__(*args,**kwargs)
        self.fields['name'].required = True
        self.fields['city'].validators.append(validate_begins)
    def clean_name(self):
        """自定义验证方法"""
        print("执行顺序2:clean_name")
        value = self.cleaned_data['name']
        if value == 'root':
            return value
        else:
            raise ValidationError("你不是管理员!")
    def clean(self):
        print("执行顺序3: name")
        # 不符合需求的字段不会出现在cleaned_data中
        cleaned_data = super(AuthorForm, self).clean()
        password = cleaned_data.get('password', '')
        password2 = cleaned_data.get('password2', '')
        if password != password2:
            raise forms.ValidationError("passwords not match")
        return cleaned_data
    class Meta:
        print("启动Django时就执行了")
        model = Author
        
        # fields = '__all__'  # 显示全部字段
        # exclude = 'title'   # 排除某个字段
        fields = ['name', 'title', 'city',]  # 决定显示哪些字段与显示顺序
        # model中指定editable=False时,任何表单都不会包含该字段。
        labels = {'name': _('姓名'),}
        help_texts = {'name': _('Some useful help text.'),}
        error_messages = {
            'name': {'required': _("This writer's name is too long."),},
            'birth_date': {'required': _("时间不能为空"),},
        }
原文地址:https://www.cnblogs.com/hanqian/p/7143155.html