开发者

Django "Duplicate" ModelForm

开发者 https://www.devze.com 2023-01-14 00:09 出处:网络
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 ce开发者_运维技巧rtain

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 ce开发者_运维技巧rtain 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.


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)


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号