I am working on a Django view which allows the user to modify an existing model object. However, when the form is submitted it creates a new object instead of modifying the existing object.
I have read the Django docs on the save() function, forms, queries, etc. but haven't been able to understand what is happening. The docs say that .save() should translate into an UPDATE statement on the database side.
I think the problem is related to the primary key for this model. I didn't define one manually. The form doesn't seem to be pulling in the ID field that Django automatically created. Since that ID didn't get passed along to .save(), it believes that I want a new object (because no pk was specified).
def modify(request, auditID):
this_audit = get_object_or_404(Audit, id=auditID)
form = auditForm(instance=this_audit)
if form.is_valid():
form.save()
return redirect('index')
And the model:
from django.db import models
class Audit(models.Model):
Inactive = '0'
Completed = '1'
InProgress = '2'
Waiting = '3'
status_choices = (
(Inactive, "This audit is inactive. It may have been cancelled or entered by mistake."),
(Completed, "This audit is completed."),
(InProgress, "This audit is currently in progress."),
(Waiting, "This audit is waiting to be started."),
)
project_number = models.CharField(max_length=10, help_text="This is the audit project number. It should be in the format <b>A-xxx-xxx</b>.")
title = models.CharField(max_length=300, help_text="This is the full audit title.")
title_short = models.CharField(max_length=100, help_text="This is a short title that will be displayed when the long title is inconvenient.")
status = models.CharField(max_length=1, choices = status_choices, default= Waiting, help_text="This is the current status of the audit.")
def __str__(self):
return self.title_short