Form、ModelForm、ModelFormSet
From:自己定义的from表单(不常用)
from django import forms class GoodsForm(forms.Form): title = forms.CharField(required=True,error_messages={'required':'商品名称不能问空'}) price = forms.IntegerField(required=True,error_messages={'required':'价格不能问空'}) source = forms.ChoiceField( required=True, error_messages={'required':'价格不能问空'}, choices=models.Source.objects.all().values_list('id','title') ) category = forms.ChoiceField( required=True, error_messages={'required': '分类不能问空'}, choices=models.Goods.category_choices ) store_room = forms.ChoiceField( required=True, error_messages={'required': '库房不能问空'}, choices=models.StoreRoom.objects.all().values_list('id','title') )
ModelForm:使用的比较多
class GoodsModelForm(forms.ModelForm): class Meta: model = models.Goods fields = "__all__" error_messages = { 'title':{'required':'商品名称不能为空'} } widgets = { 'source':forms.RadioSelect() } def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) for name,field in self.fields.items(): if name == 'source': # print(field,type(field)) # from django.forms.models import ModelChoiceField field.empty_label = None else: field.widget.attrs['class'] = 'form-control'
ModelFormSet:批量操作的时候使用
视图: 导入模块 from django.forms.models import modelformset_factory 使用:modelformset_factory(model=models.Goods(models.类),form=GoodsModelForm(你自己写的modelfrom),extra=1(有几个空余)) form_set = modelformset_factory() :使用需要实例化 当返回的时候 form_set = GoodsModelFormSet(data=request.POST) if form_set.is_valid(): form_set.save() 模板: 两个东西必须加 每一条数据的id {{form_set.management_form}} 这样才不会报错