Django ModelForm 不更新实例,但因 IntegrityError 失败

问题描述 投票:0回答:1

我遇到了一些非常奇怪的问题。它不会保存实例,而是尝试使用相同的主键创建实例。

ModelForm

django.db.utils.IntegrityError:重复的键值违反了唯一约束“foundry_upload_pkey”
详细信息:密钥 (id)=(1) 已存在。

我确信这是一个非常微不足道的错误,但我只是无法发现我哪里出了问题;在我看来,这看起来和
教科书上的例子

一模一样。 class Upload(models.Model): file = models.FileField(upload_to=get_foundry_upload_name, null=False, blank=False) filename = models.CharField(max_length=256, null=True, blank=True) foundry = models.ForeignKey(Foundry, on_delete=models.CASCADE) family = models.CharField(max_length=256, null=True, blank=True) family_select = models.ForeignKey(Family, null=True, blank=True, on_delete=models.CASCADE) style = models.CharField(max_length=256, null=True, blank=True) style_select = models.ForeignKey(Style, null=True, blank=True, on_delete=models.CASCADE) processed = models.BooleanField(default=False) created = models.DateTimeField("Created", auto_now_add=True) class UploadProcessForm(ModelForm): class Meta: model = Upload fields = ( "filename", "family", "family_select", "style", "style_select", ) def upload_process_row(request, foundry, id): i = get_object_or_404(Upload, id=id, foundry=foundry) upload_form = UploadProcessForm(instance=i) if request.method == "POST": upload_form = UploadProcessForm(request.POST, instance=i) if upload_form.is_valid(): upload_form.save() return render(request, "foundry/upload_process.row.html", { "f": upload_form }) 始终尝试使用实例的主键“创建”数据库条目。我只想更新现有实例(这就是

upload_form.save()
的全部意义,不是吗?)。 为了确定起见,我已经擦除了数据库表和迁移并重新创建了它们。
    

由于缺乏上下文,我无法提供可靠的解决方案,但您可以尝试一些方法来解决该问题。

python django django-forms modelform
1个回答
0
投票

ModelForm

调用之前添加调试语句,以确认

save()

确实是同一个对象,而不是新对象:

upload_form.instance
您可以显式设置主键作为临时解决方法

print(upload_form.instance.id)

© www.soinside.com 2019 - 2024. All rights reserved.