我有一个使用默认{{ formset }}呈现的{{ formset }} 。 提交表单时,页面会回复自己的帖子。
问题是当创建新实例时,包含id的字段仍然是空白的,如<input id="id_form-0-id" name="form-0-id" type="hidden"> 。 因此,如果我在表单返回后重新提交表单,它最终会创建新实例,而不是更新新创建的实例。 如果我刷新页面,则字段包含ids <input id="id_form-0-id" name="form-0-id" type="hidden" value="18"> 。
这是我的控制器功能:
def main_categories (request): dict = {} FormSet = modelformset_factory (MainCategory, formset = MainCategoryFormSet, fields = ['name'], extra = 1, can_delete = True) if request.method == 'POST': formset = FormSet (request.POST) if formset.is_valid (): with transaction.atomic (): formset.save () else: formset = FormSet () dict ['formset'] = formset return render (request, 'equipment/admin/main_categories.html', dict)I have a formset that I am rendering with the default {{ formset }}. The page does a post back to itself when the form is submitted.
The issue is when new instances are created, the fields containing the ids are still blank like <input id="id_form-0-id" name="form-0-id" type="hidden">. So if I resubmit the form after it comes back, it ends up creating new instances instead of updating the newly-created instances. If I refresh the page then the fields contain the ids <input id="id_form-0-id" name="form-0-id" type="hidden" value="18">.
This is my controller function:
def main_categories (request): dict = {} FormSet = modelformset_factory (MainCategory, formset = MainCategoryFormSet, fields = ['name'], extra = 1, can_delete = True) if request.method == 'POST': formset = FormSet (request.POST) if formset.is_valid (): with transaction.atomic (): formset.save () else: formset = FormSet () dict ['formset'] = formset return render (request, 'equipment/admin/main_categories.html', dict)最满意答案
如果要编辑以前提交的查询集,则必须在FormSet类中提供queryset。 见文档
If you want to edit previously submitted queryset, you must provide queryset into FormSet class. See documentation
更多推荐
发布评论