姜戈“重复”模型表单
我想知道是否有一种简单的方法在 Django 中创建“重复”ModelForm - 即预先填充现有模型实例内容的表单(某些字段除外,例如唯一的字段),但创建一个保存时的新实例。
我正在考虑向 ModelForm 提供一个实例,以便数据像“编辑”表单一样预先填充,然后在保存之前将实例设置为 None,但这给出了“'NoneType' 对象没有属性 'pk' '”在表单上调用 .save() 时出错。构建表单时提供实例的行为似乎会产生对其最终存在的某种依赖性。
我很难找到这个问题的解决方案,但我无法想象“重复”的形式太独特,所以也许我错过了一些简单的东西?
任何帮助将不胜感激。
I'm wondering if there is a simple way of creating a "duplicate" ModelForm in Django - i.e. a form that is prefilled with the content of an existing model instance (excepting certain fields, such as those that are unique), but creates a new instance when saved.
I was thinking along the lines of supplying an instance to a ModelForm so that the data is prefilled as with an "edit" form, then setting the instance to None before saving, but this gives a "'NoneType' object has no attribute 'pk'" error when calling .save() on the form. It seems the act of supplying an instance when constructing the form creates some dependency on it being there at the end.
I have had trouble finding a solution to this problem, but I can't imagine a "duplicate" form being too unique, so maybe I am missing something simple?
Any help would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您需要的是一种填写表单中字段的初始值的方法。实现此目的的最佳方法是从现有实例创建初始值字典(由字段名称作为键)并将其提供给表单。
像这样的事情:
I think what you need is a way to fill in the initial values for the fields in the form. The best way to accomplish this would be to create a dictionary of initial values (keyed by field name) from an existing instance and supply this to the form.
Something like this: