ModelForm表单验证

form与model的终极结合,具有以下功能:验证、数据库操作。

# 写一个和Model类一一对应的form
from django import forms

class BookModelForm(forms.ModelForm):

    class Meta:
        model = models.Book     #对应的model中的类
        fields = "__all__"  # model类里所有的字段都展示
        # fields = ["title",]   # 指定展示某些字段
        exclude = None    #除了指定字段,其他字段都显示
        labels = {              #设置label标签名
            "title":"书名",
            "phone":"手机号",
            "publish_date":"出版日期",
            "publisher":"出版社",
            "authors":"作者",
        }
        widgets = {             #设置每个字段的插件信息
            "title":forms.widgets.TextInput(attrs={"class":"form-control"}),
            "phone": forms.widgets.TextInput(attrs={"class": "form-control"}),
            "publish_date":forms.widgets.DateInput(attrs={"type":"date","class":"form-control"}),
            "publisher": forms.widgets.Select(attrs={"class": "form-control"}),
            "authors": forms.widgets.SelectMultiple(attrs={"class": "form-control"}),
        }
        error_messages = {      #设置每个字段的报错提示信息
            "publisher":{
                "required":"必须选一个出版社!"
            }
        }
class Meta: 常用参数
model = models.Student  # 对应的Model中的类
fields = "__all__"  # 字段,如果是__all__,就是表示列出所有的字段
exclude = None  # 排除的字段
labels = None  # 提示信息
help_texts = None  # 帮助提示信息
widgets = None  # 自定义插件
error_messages = None  # 自定义错误信息
instance = book_obj     #实例名

 

转载于:https://www.cnblogs.com/liubailiang/p/11470756.html

你可能感兴趣的:(ModelForm表单验证)