Code:
Model:
class Machines(models.Model):
name = models.CharField(max_length=100, verbose_name="hostname", help_text="Host name of the machine")
ip_addr = models.CharField(max_length=50, primary_key=True, help_text="IP address of the machine")
.... have many other fields.
Form:
Using forms.ModelForm to create a form
View:
def save(request):
if request.method == "POST":
ip = request.POST.get("ip")
machine = get_object_or_404(Machines, ip_addr=ip)
form = MachineForm(instance=machine, data=request.POST)
if form.is_valid():
if form.has_changed():
form.save()
context = {"message": "Updated successfully"}
else:
context = {"message": "No data to update"}
return render_to_response("edit.html", context, context_instance=RequestContext(request))
If I change “name” field, form.save() updates the current object properly. But, if I change “ip_addr” field which is primary key, form.save() creates two entries one with old primary key other with new primary key.
If we do same in MySQL(BTW, I am using MySQL as DB)
update machines_table set ip_addr="10.1.1.1" where ip_addr="10.1.1.2";
It works fine, there will not be any duplicate entry.
Can you please help me out.
What you’re doing is updating private key. Django creates new instance in this case. It is is actually Django’s way to copy a record. The
INSERTnotUPDATEquery is performed by ORM.If you change your code to:
Django will interprete your edit action correctly as the primary key won’t change.
Next time use
django-debug-toolbarto see what query is performed by Django ORM.