简体   繁体   中英

django update view adds a record instead of replacing the updated one

this is my Django view for the update form views.py

def updatebc(request, pk):
    instance = get_object_or_404(BaseCase, pk=pk)
    instance.base_case_name
    bcform = BaseCaseForm(request.POST or None,instance=instance)
    if bcform.is_valid():
        instance = bcform.save(commit=False)
        instance.save()
    context = {
        'bcform':bcform,
    }
    return render(request, 'update.html', context)

and here is my models.py

class BaseCase(models.Model):
    base_case_name = models.CharField(primary_key=True, max_length=255)
    version = models.TextField(blank=True, null=True)
    default = models.TextField(blank=True, null=True)  # This field type is a guess.

    class Meta:
        managed = False
        db_table = 'base_case'

when I try to update a record I actually add one instead of replacing it !

As mentioned in django docs :

The primary key field is read-only. If you change the value of the primary key on an existing object and then save it, a new object will be created alongside the old one.

You are changing the primary key field base_case_name , so instead of updating the instance, django will create a new one.

def updatebc(request, pk):
    instance = get_object_or_404(BaseCase, pk=pk)
    instance.base_case_name
    bcform = BaseCaseForm(request.POST or None,instance=instance)
    if bcform.is_valid():
        instance = bcform.save(commit=False)
        instance.save()
    context = {
        'bcform':bcform,
        'instance': instance,
    }
    return render(request, 'update.html', context)

Pass instance also to your template and see

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM