Django Django如何知道哪个表单集是哪个 [英] Django how does Django know which formset is which

查看:76
本文介绍了Django Django如何知道哪个表单集是哪个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 假设我有一个直接对应于ModelFormset的模型.
  2. 假设模型的三个实例保存在数据库中.
  3. 假设我用初始数据=三个实例加载了ModelFormset
  4. 现在,我在页面上呈现ModelFormset供用户修改.
  5. 修改后,用户单击提交.我怎么知道哪个ModelFormset对应于数据库中保存的Model的哪个实例?

更新:

我正在阅读以下示例: https://docs.djangoproject.com/en/1.9/topics/forms/formsets/#formsets-initial-data

I was reading this example: https://docs.djangoproject.com/en/1.9/topics/forms/formsets/#formsets-initial-data

在此示例中,初始数据是手动提供的.假设初始数据是否像这样传递:

In this example, the initial data was provide manually. Assuming if the the initial data was passed in like this:

article = Article.objects.get(pk=...)
formset = ArticleFormSet(initial=[
    model_to_dict(article)
])

将此 formset 发送到模板时,文章的ID是否保留在呈现的HTML中?如果没有,那么如果对文章进行了修改并提交,Django如何知道应该更新哪篇文章?

When this formset is sent to the template, is article's id preserved in the rendered HTML? If not, then how does Django know which article it should update if modifications to the article has been made and submitted?

推荐答案

如果您在 ModelForm 中(或在ModelFormset中的一组实例中)有一个现有实例,则存在一个隐藏字段,其中包含记录主键的值.

If you have an existing instance in ModelForm (or in a set of them inside ModelFormset), then there's a hidden field with the value of the primary key for the record.

每个 ModelForm 的每个字段都有一个唯一的后缀,有助于区分哪些字段属于同一模型.

Each ModelForm has also a unique suffix for each the field, which helps distinguish which fields belongs to the same model.

这篇关于Django Django如何知道哪个表单集是哪个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆