代码
from django import forms
from django.forms import widgets as wig # 因为重名,所以起个别名
from django.shortcuts import render
from app01.models import Book
class BookModel(forms.ModelForm):
class Meta:
model = Book # 对应的model对象
# 包括哪些字段
fields = "__all__"
# fields = ['title','price']
# 不包括
# exclude = ['title']
labels = {
'title': '书籍名称',
'price': '价格'
}
error_messages = {
'title': {'required': '标题错误'},
'price': {'required': '价格输入有误'}
}
widgets = {
"title": wig.TextInput(attrs={'class': 'c1'})
}
#钩子函数和form一样
def clean_price(self):
pass
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for fields in self.fields.values():
fields.widget.attrs.update({'class': 'form-control'})
# Create your views here.
def index(request):
if request.method == "GET":
# 模型直接渲染页面
book = BookModel()
# 带值,渲染
book = BookModel(instance=Book.objects.filter(pk=1).first())
return render(request, '1.html', locals())
else:
book = BookModel(request.POST)
if book.is_valid():
# 数据直接存储到数据库
book.save()
# book = BookModel(request.POST,instance=book_01) 指定了对应到图书内容
# book.save() #这里就update操作
return render(request, '1.html', locals())