tags:

views:

40

answers:

2

Hi there, probably a silly question, but I'm not sure how to handle this 'correct'.

I got a normal form with some fields. I can insert data without problems. When I want to edit a record, I'm using the "model_to_dict"-function to populate the form. After editing a record I want so save it, and here my problems starts.

The django docs says that a model does automatically create or update the record depending on the pk-value. if the pk-value exists, its an update, otherwise an insert. So I've created this save-function:

def save(self, primary_key=0):
    mymodel = Somemodel(pk=primary_key,
        samplefield=self.cleaned_data['samplefield'],
    )
    mymodel .save()
    print 'PK:'+str(d.pk)
    # Handle the MultipleChoiceField's
    for x in self.cleaned_data['paymentMethod']:
        x.mymodel_set.add(d)

So, this works fine when I edit an record. But when I insert a new record, it gets inserted fine, but mymodel.id = 0 which means I can't save the relations for the MultipleChoiceFields.

So I would like to know if this is a good way to handle this? And why is mymodel.id = 0 after saving the model?

A: 

0 is a valid integer PK. Use None instead.

Ignacio Vazquez-Abrams
Great that works! Thanks a lot ;)
Ben
A: 

Firstly, why aren't you using a ModelForm? That is the right way to handle this situation.

In answer to your question 'why is the pk 0', it's because you've explicitly set it to be 0 if a PK isn't passed into the function. If you don't want to set it to 0, use None as the default.

Daniel Roseman
Hi Daniel,I'm using a normal form because I've trouble handling extra fields on many-to-many relationships on modelForms.
Ben