Situation: Have an existing mysql database with some data. For this example, I only use two fields; id and subject. id is defined as Integer with the *auto_increment* option, while subject is just a normal varchar. The code:
Model:
class AList(models.Model):
id=models.AutoField(primary_key=True, db_column='ID')
subject=models.CharField(max_length=200, db_column='SUBJECT')
class Meta:
db_table = u'alist'
Form:
class AForm(ModelForm):
class Meta:
model=AList
View:
def alistForm(request,a_id=None):
if a_id:
a=AList.objects.get(id=a_id)
form=AForm(instance=a)
else:
form=AForm(request.POST or None)
return render_to_response('aform.html',{'form':form},context_instance=RequestContext(request)
def alistPost(request):
form=AForm(request.POST or None)
if form.is_valid():
form.save()
Description of the problem: When the form sends new data to the alistPost-function, the form.save() inserts a new record as it should. But when I edit an already existing record, that too is inserted as a new record... and not updated as it should do.
Trying to change the id from AutoField to an IntegerField changes the behavior: Modifying a record makes form.save() to modify the existing one, while trying to insert a new record it fails because it does not have an id.
Question: Do I manually have to get a new ID-value from the database and force Django to use it for this new record, or is there a way to make Django automagically figure out if it should use INSERT or UPDATE?