在书店应用程序中,我有一个表单,用于添加由Book
编写的Author
和属于Shelf
的{{1}}。书需要与书架相关联。
Bookstore
我的问题是:实际上有更简洁的方式来写这个吗?我很确定有,但我在某处错过了。
答案 0 :(得分:1)
试一试
class AddFruitForm(forms.Form):
def save(self, request):
# list all your fields here
fields_expected = ['fruit_name', 'fruit_color', ...]
# this should give you the dict with all the fields equal to "None"
fields = dict.fromkeys(fields_expected)
# this relace the None value with the good data from cleaned_data
fields.update(self.cleaned_data)
# assign all the in the dict to the model, key=value
fruit = Fruit(**fields)
fruit.save(force_insert=True, force_update=False)
但是,如果您的模型可以为这些值接受None,则不必如上所述明确提供给模型,您可以改为使用模型来处理默认值。
class AddFruitForm(forms.Form):
def save(self, request):
fields = self.cleaned_data
fields['my_custom_field'] = 'some data not from the field'
fruit = Fruit(**fields)
fruit.save(force_insert=True, force_update=False)
答案 1 :(得分:1)
如果您的数据与模型相关联,则最好使用ModelForm
。您可以在前端拥有任意数量的表单并完全提交。代码非常简单:
# models.py
class BookForm(forms.ModelForm):
class meta:
model = Book
class Shelf(forms.ModelForm):
class meta:
model = Shelf
# views.py
def addbook(request):
book_form = BookForm(request.POST or None)
shelf_form = SelfForm(request.POST or None)
if book_form.is_valid() and shelf_form.is_valid():
book = book_form.save()
shelf = shelf_form.save()
return redirect('some-list-view')
return render(request,
'addbook.html',
{'book_form': book_form, 'shelf_form': shelf_form})
# addbook.html
<form action="/addbook/" method="post">
{% csrf_token %}
{{ book_form }}
{{ shelf_form }}
<input type="submit" value="Submit" />
</form>