0

I have django model form MyModelFormA for the model ModelA (I am using these in FormView).

I want to pass initial values to the form using existing object of ModelA and create new object of it if changes occur.

I have been passing initial values like below:

def get_form_kwargs(self):
    kwargs = super(MyFormView, self).get_form_kwargs()
    kwargs.update({'instance': ModelAObject})

I'm not sure why but when the form is validated like below

def form_valid(self, form):
    instance = form.save()

Its just updating existing instance object instead of creating new.

  1. HTTP requests being stateless, how does the request knows an instance that is being passed processed in previous request

  2. How to solve this?

I thought of doing something like

def get_initial(self):
    initial = model_to_dict(MyModelAObject)
    return initial

Actually There are only a subset of MyModelA fields in MyModelFormA. Passing all fields as dict initially, wouldn't create any trouble?

is there any much elegant way to handle it?

4
  • How do you get ModelAObject? Commented May 5, 2014 at 6:02
  • I get it from database! ModelA.objects.get() Commented May 5, 2014 at 6:11
  • But how do you get some particular object? Commented May 5, 2014 at 6:19
  • well, the url endpoint is something like /pk/edit. So, I get the object from there which I evaluate in dispatch() Commented May 5, 2014 at 6:53

2 Answers 2

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,
      ....
  }
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

If the form passes pk value to the template as hidden field, isn't that create security loop holes? For instance, users can go and edit pk value and make the form believe it comes from wrong object!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.