[Answer]-Django pass initial values from object in Model Form

1๐Ÿ‘

  1. When you pass ModelForm an instance, it sets id field of that instance as initial of the form as well. So, if it receives an ID in the POST, its treats it as a existing object and updates it

  2. You will need to pass individual fieldโ€™s initial value(i.e except id). The best way is to only pass the fields you need, in ModelForm, as initial.

def get_initial(self):
  return {
      'a': MyModelAObject.a,
      ....
  }
๐Ÿ‘คSahil kalra

0๐Ÿ‘

Probably you can try this:

def form_valid(self, form):
    if form.has_changed()
        instance = form.save(commit=False)
        instance.pk = None
        #if you have id 
        instance.id = None
        instance.save() #will give you new instance.

Check In Django 1.4, do Form.has_changed() and Form.changed_data, which are undocumented, work as expected? to see how form.has_changed() will work.

๐Ÿ‘คRohan

Leave a comment