python - 如何处理 Django 元类中的 UniqueConstraint 失败?

标签 python django

我为我的模型创建了一个 UniqueConstraint 元类,当我通过故意创建重复项来测试它时,它可以工作,但我收到一个错误页面,而不是被重定向回原始页面。我在哪里插入代码以返回到我刚才所在的页面?

我认为问题出在 View 中,但我不知道要在其中放入什么代码,并且 Django 文档不包含任何暗示此问题的内容。

型号:

class StudentScheduledClass(models.Model):
    student = models.ForeignKey("users.User", on_delete=models.CASCADE, db_column="Student")
    scheduled_class = models.ForeignKey("ScheduledClass", on_delete=models.CASCADE, db_column="ScheduledClass")
    grade = models.FloatField(db_column="Grade", blank=True, null=True)

    class Meta:
        managed = True
        db_table = "StudentScheduledClass"
        verbose_name_plural = "StudentsScheduledClasses"
        constraints = [
            models.UniqueConstraint(fields=['student', 'scheduled_class'], name='student scheduled class restraint')
        ]

查看:

class StudentScheduledClassCreateView(LoginRequiredMixin, CreateView):
    model = StudentScheduledClass
    context_object_name = "student_scheduled_class"
    fields = ["student"]

    def form_valid(self, form):
        scheduled_class = self.kwargs["scheduled_class"]
        form.instance.scheduled_class = ScheduledClass(scheduled_class)
        return super().form_valid(form)

    def get_success_url(self):
        scheduled_class = self.kwargs["scheduled_class"]
        return reverse("scheduled-class-detail", args={scheduled_class})

我只想返回原始页面并显示错误消息,但我收到了此完整性错误:

IntegrityError at /classes/student_scheduled_class_create/1/
UNIQUE constraint failed: StudentScheduledClass.Student, StudentScheduledClass.ScheduledClass
Request Method: POST
Request URL:    http://localhost:8000/classes/student_scheduled_class_create/1/
Django Version: 2.2.2
Exception Type: IntegrityError
Exception Value:    
UNIQUE constraint failed: StudentScheduledClass.Student, StudentScheduledClass.ScheduledClass

最佳答案

您的表单仅需要字段 student所以它是有效的,因为您没有为其实例指定 scheduled_class 的值当它得到验证时。

您应该使用instance来初始化您的表单。其中scheduled_class已设置。您可以在get_form_kwargs()中做到这一点或者,因为该方法通过 self.objectinstance ,您可以在post()中更简单地做到这一点:

def post(self, request, *args, **kwargs):
    self.object = StudentScheduledClass(scheduled_class=kwargs['scheduled_class'])
    return super().post(request, *args, **kwargs)

或者,虽然有点不太干净(我喜欢认为一旦 form_valid() 被调用,一切都应该没问题):

def form_valid(self, form):
    scheduled_class = self.kwargs["scheduled_class"]
    form.instance.scheduled_class = ScheduledClass(scheduled_class)
    try:
        return super().form_valid(form)
    except IntegrityError:
        return self.form_invalid(form)

最后一个的问题是表单不会显示任何错误,因此您可能需要向 self.request 添加一条 Django 消息。返回之前(假设您在模板中显示任何消息)。

关于python - 如何处理 Django 元类中的 UniqueConstraint 失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56464657/

相关文章:

python - df.iloc 未在 For 循环中赋值? ( Pandas )

python - 创建包时,如何管理弱依赖项的迁移?

python - Heroku 部署错误 : No matching distribution found for en-core-web-sm

python - 元组拆包顺序更改分配的值

python - 从 Jupyter notebook 中删除空行

Django ForeignKey 实例与原始 ID

javascript - 使用 Django 的 jQuery/JavaScript 弹出窗口(从子项中选择,在父项中显示)

database - 现场冲突的django related_name

python - 如何从代码中检查当前实例的内存使用情况

python - 再现全连接顺序层