我有一个formset,但我无法弄清楚如何使用数据库中的数据预先填充它。
说实话,我有一个模型库和一个具有Library外键的模型Book。我希望有人能够在一个库中一次编辑所有书籍。
HTML
{{ book_form.management_form }}
{% for form in book_form.forms %}
{{ form.as_p }}
{% endfor %}
views.py
class LibraryUpdateView(LoginRequiredMixin, UpdateView):
model = Library
form_class = LibraryChangeForm
template_name = 'libraries/library_update.html'
def get_context_data(self, *args, **kwargs):
context = super(LibraryUpdateView, self).get_context_data(*args, **kwargs)
if self.request.POST:
context['book_form'] = BookFormSet(self.request.POST)
else:
context['book_form'] = BookFormSet()
return context
形式
class LibraryChangeForm(forms.ModelForm):
class Meta:
exclude = ['updated']
BookFormSet = inlineformset_factory(Library, Book, exclude = () )
如何预填充html页面以显示formset中的数据。在我的循环中,{{form.as_p}}
有3个循环。当我运行print(BookFormsSet())
时,我会看到以下内容
<input type="hidden" name="perdateinfo_set-TOTAL_FORMS" value="3"...
所以看起来它生成了三个空白表格。
当我为print(PerDateInfoFormSet(qs,qs2))
运行qs = Library.objects.filter(library_id='slkdfj') and qs2=Book.objects.filter(library_id='slkdfj')
时,它会告诉我too many values to unpack (expected 2)
我可以传入查询集吗?我想我会传入qs.first()来获取库,然后传递多个(qs2)查询集来获取库中的所有书籍。
答案 0 :(得分:1)
您需要将实例参数传递给formset:
def get_context_data(self, *args, **kwargs):
context = super(LibraryUpdateView, self).get_context_data(*args, **kwargs)
if self.request.POST:
context['book_form'] = BookFormSet(self.request.POST, instance=self.object)
else:
context['book_form'] = BookFormSet(instance=self.object)
return context