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

时间:2019-01-23 03:40:06

标签: python django

我的公司当前正在使用自定义任务管理库(视图流),并且给我一个UpdateProcessView。该视图更新了控制所有任务的流程,并且仅在满足某些条件的情况下,我才想覆盖此过程以验证调用form_valid

由于我无法控制提交给该视图的表单,因此无法编写自定义表单来进行验证(我们之前曾尝试过此操作,但变得非常混乱)。

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

2 个答案:

答案 0 :(得分:0)

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

id

答案 1 :(得分:0)

如果我确实了解您的问题和问题,我认为您正在尝试执行以下示例:

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