为什么我的表单创建一个新的模型对象而不是修改一个?

时间:2017-10-11 02:40:49

标签: python django django-models django-forms

我正在开发一个允许用户修改现有模型对象的Django视图。但是,在提交表单时,它会创建一个新对象,而不是修改现有对象。

我已经阅读了关于save()函数,表单,查询等的Django文档,但是我们无法理解正在发生的事情。文档说.save()应该转换为数据库端的UPDATE语句。

我认为问题与此模型的主键有关。我没有手动定义一个。表格似乎并没有拉入Django自动创建的ID字段。由于该ID没有传递给.save(),因此它认为我想要一个新对象(因为没有指定pk)。

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')

模特:

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

1 个答案:

答案 0 :(得分:2)

这样会更好,是一种更好的做法

def modify(request, auditID):
    this_audit = get_object_or_404(Audit, id=auditID)

    form = auditForm(request.POST, instance=this_audit)

    if form.has_changed():
        if form.is_valid():
            form.save()

    return redirect('index')

参考https://docs.djangoproject.com/en/1.11/topics/forms/modelforms/#the-save-method。我不确定但基本上问题是您必须使用request.POST