我遇到了一些非常奇怪的问题。它不会保存实例,而是尝试使用相同的主键创建实例。
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()
的全部意义,不是吗?)。
为了确定起见,我已经擦除了数据库表和迁移并重新创建了它们。
由于缺乏上下文,我无法提供可靠的解决方案,但您可以尝试一些方法来解决该问题。