如何使用新的pk id更新formset?(How to update formset with new pk id?)

编程入门 行业动态 更新时间:2024-10-21 04:04:57
如何使用新的pk id更新formset?(How to update formset with new pk id?)

我有一个使用默认{{ 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

更多推荐

本文发布于:2023-08-07 02:24:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1458885.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   pk   id   formset   update

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!