views:

46

answers:

2

Hi

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.

+1  A: 

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)
Manoj Govindan
+1  A: 
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)
Pydev UA
This doesn't seem to work as altering the pk property does not seem to alter the actual primary key field ('id' in my case). Thus, the ModelForm still overwrites the existing object as opposed to creating a new one.
oogles