如何在UpdateView中进行验证而不通过表单进行验证?

2024-06-10 12:54:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我的公司目前正在使用一个定制的任务管理库(viewflow),我得到了一个UpdateProcessView。视图更新了管理所有任务的进程,我想重写它,仅在满足某些条件时验证调用form_valid。你知道吗

因为我无法控制提交给这个视图的表单,所以编写一个自定义表单来验证是不可能的(我们以前尝试过这个方法,结果非常混乱)。你知道吗

在这种情况下,下一个插入验证逻辑的最佳位置是哪里?我正在检查self.model中是否存在某些字段。你知道吗


Tags: 方法selfform视图表单model进程情况
2条回答

如果我真的很理解你的问题和你的问题,我想你是在尝试这样的例子:

from django.shortcuts import redirect
from django.urls impot reverse_lazy
# If you want to use the django's messages framework
from django.contrib import messages

class MyCustomView(UpdateProcessView):
    def __init__(self, *args, **kwargs):
        # Initialize the parents of MycustomView class
        super().__init__(self, *args, **kwargs)

    # Then override form_valid method
    def form_valid(self, form):
        # You need to verify is self.model is iterable or not
        # If not, you need to find a way to pass your conditions 
        # with self.model elements
        if 'elm1' in self.model:
            messages.error(self.request, "Condition 1 is not met")
            return redirect(reverse_lazy('my_url1_name'))
        elif 'elm2' in self.model:
            messages.error(self.request, "Condition 2 is not met")
            return redirect(reverse_lazy('my_url2_name'))

        messages.success(self.request, "Valid request")
        # which will return a HttpResponseRedirect
        return super().form_valid()

我认为您可以研究Model的clean方法。您可以这样尝试:

from django.core.exceptions import ValidationError

class YourModel(models.Model):
    ...
    def clean(self):
       if self.something is 'wrong':
           raise ValidationError("Something is wrong")

    def save(self, *args, **kwargs):
        self.full_clean()
        return super(YourModel, self).save(*args, **kwargs)

相关问题 更多 >