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?
0is a valid integer PK. UseNoneinstead.