Django ModelForm
ModelForm 用于将数据库中表的各个字段做为form进行生成及验证
视图
# views.py
def book_modelform(reqeust):
form = froms.BookModelForm()
if request.method == 'POST'
form = froms.BookModelForm(request.POST)
if form.is_valid():
form.save()
return render(request, 'app01/book_form.html', {'book_form':form})
自定义的forms.py
# froms.py
from app01 import models # 导入models
class BookModelForm(forms.ModelForm):
class Meta:
model = models.Book
fields = ('name', 'publish_date') # 设置fields则处理指定的字段
# exclude = () # exclude指排除哪些字段,如果要显示所有字段使用exclude = ()
widgets = {
'name' : forms.TextInput(attrs={'class':'form-control', 'placeholder':'请输入姓名'}) # 给字段加属性
}
# 扩展,给ModelForm中所有的标签都加上样式
def __init__(self, *args, **kwargs):
super(BookModelForm, self).__init__(*args, **kwargs)
for field_name in self.base_fields:
field = self.base_fields[field_name]
field.widget.attrs.update({'class': 'form-control'})
数据库
# models.py
class Book(models.Model):
name = models.CharField(max_length=128)
authors = models.ManytoManyField(Author)
publisher = models.ForeignKey(Publisher)
publish_date = models.DateField()
前端
# app01/book_form.html
<form action='app01/book_form.html' method='post'>
{% crsf_token %}
{{ book_form }}
</form>