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 %}