标签:log obj 转换 tip mode tps blog publish instance
24 Jul 18 (ModelForm)
https://www.cnblogs.com/yuanchenqi/articles/8034442.html
如果不用ModelForm,将Model手动转成Form时,对于非一对一字段,可能要使用以下字段类:
ChoiceField是Field的子类:拿从内存中取的数据时用
ModelChoiceField 是ChoiceField的子类: 拿从数据库中取的数据时用(多对一)
ModelMultipleChoiceField是ModelChoiceField的子类: 拿从数据库中取的数据时用(多对多)
is_pub=forms.ChoiceField(choices=((1,"出版"),(2,"未出版"),))
publish=forms.ModelChoiceField(queryset=Publish.objects.all())
authors=forms.ModelMultipleChoiceField(Author.objects.all())
ModelForm: 将Model转换成Form,从而进行下一步调用
class BookModelForm(forms.ModelForm):
class Meta:
model=Book
fields="__all__"
添加表单:
GET:
form=BookModelForm()
form:渲染
POST:
form=BookModelForm(request.POST)
form.is_valid()
form.save() # 添加数据create
编辑表单:
edit_book = Book.objects.get(pk=id)
GET:
form=BookModelForm(instance=edit_book)
form:渲染
POST:
form=BookModelForm(request.POST,instance=edit_book)
form.is_valid
form.save() # 更新数据update
标签:log obj 转换 tip mode tps blog publish instance
原文地址:https://www.cnblogs.com/zhangyaqian/p/py20180724.html