姜戈“重复”模型表单

发布于 2024-09-17 00:53:28 字数 321 浏览 9 评论 0原文

我想知道是否有一种简单的方法在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦醒灬来后我 2024-09-24 00:53:28

我认为您需要的是一种填写表单中字段的初始值的方法。实现此目的的最佳方法是从现有实例创建初始值字典(由字段名称作为键)并将其提供给表单。

像这样的事情:

class AddressForm(forms.ModelForm):
    class Meta:
        model = Address

# Inside view:
address = Address.object.get(**conditions)
initial = dict()
for field in ('state', 'zipcode'): # Assuming these are the fields you want to pre-fill
    initial[field] = getattr(address, field)

form = AddressForm(initial = initial)

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:

class AddressForm(forms.ModelForm):
    class Meta:
        model = Address

# Inside view:
address = Address.object.get(**conditions)
initial = dict()
for field in ('state', 'zipcode'): # Assuming these are the fields you want to pre-fill
    initial[field] = getattr(address, field)

form = AddressForm(initial = initial)
和影子一齐双人舞 2024-09-24 00:53:28
class AddressForm(forms.ModelForm):
    class Meta:
        model = Address

# Inside view:
address = Address.object.get(pk=<your-id>)
address.pk = None # that's the trick, after form save new object will be created
form = AddressForm(instance=address)
class AddressForm(forms.ModelForm):
    class Meta:
        model = Address

# Inside view:
address = Address.object.get(pk=<your-id>)
address.pk = None # that's the trick, after form save new object will be created
form = AddressForm(instance=address)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文