1 gender = forms.ChoiceField(choices=((1, '男'), (2, '女'), (3, '其余'))) # 与sql不要紧 2 publish = forms.ChoiceField(choices=Publish.objects.all().values_list('pk', 'name')) 3 publish = forms.ModelChoiceField(queryset=Publish.objects.all(), label='出版社') 4 authors = forms.ModelMultipleChoiceField(queryset=Author.objects.all(), label='做者')
-------->forms在post提交数据时,能够验证并将数据返回前端,html
get请求时,如何将数据返回前端?前端
1 from django.forms import ModelForm 2 from django.forms import widgets as wid # 由于重名,因此起个别名! 3 class BookForm(ModelForm): 4 class Meta: 5 model = Book # 关联的哪一个模型 6 fields = "__all__" # 对全部字段转换 ["title",...] 7 exclude = None # 排除的字段 8 9 # 自定义在前端显示的名字 10 labels = {"title": "书籍名称", "price": "价格", "date": "日期", "publish": "出版社", "authors": "做者"} 11 widgets = { 12 'title': wid.TextInput(attrs={'class': 'form-control'}), 13 'price': wid.TextInput(attrs={'class': 'form-control'}), 14 'date': wid.TextInput(attrs={'class': 'form-control', 'type': 'date'}), 15 'publish': wid.Select(attrs={'class': 'form-control'}), 16 'authors': wid.SelectMultiple(attrs={'class': 'form-control'}) 17 } 18 error_messages = { 19 'title': {'required': '不能为空'}, 20 'price': {'required': '不能为空'}, 21 'date': {'required': '不能为空', 'invalid': '格式错误'}, 22 'publish': {'required': '不能为空'}, 23 'authors': {'required': '不能为空'}, 24 }
1 # editdisplay 2 edit_book = Book.objects.filter(pk=edit_book_id).first() 3 # form = BookForm(initial={"title": edit_book.title, "price": edit_book.price, "date": edit_book.date, 4 # "publish": edit_book.publish, 'authors': edit_book.authors.all()}) 5 form = BookForm(initial=edit_book) 6 return render(request, "edit.html", locals())
1 # create、update 2 form = BookForm(request.POST) # create 3 if form.is_valid(): 4 form.save() # form.model.objects.create(request.POST) 5 6 form = BookForm(request.POST,instance=edit_book) # update 7 if form.is_valid(): 8 form.save() # edit_book.update(request.POST)
1 # display 2 {% for book in book_list %} 3 <tr> 4 <td>{{ book.title }}</td> 5 <td>{{ book.price }}</td> 6 <td>{{ book.date|date:"Y-m-d" }}</td> 7 <td>{{ book.publish.name }}</td> 8 <td>{{ book.authors.all }}</td> 9 <td><a href="/book/edit/{{book.pk}}"><button>编辑</button></a></td> 10 </tr> 11 {% endfor %}