django - how to save form (not a modelForm)
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 w开发者_JS百科orks 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?
0
is a valid integer PK. Use None
instead.
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.
精彩评论