【问题标题】:django: exclude fields from validation dynamicallydjango:动态地从验证中排除字段
【发布时间】:2013-07-18 19:25:05
【问题描述】:

我有一个表格来处理产品的添加和修改。 添加产品时,我想从验证中排除 modifyAttribute 字段,而当我修改产品时,我想从验证中排除 addAttribute 字段。

当我为 addAttribute 字段输入值时,我处于“添加模式”,当我为 modifyAttribute 字段(文本框)输入值时,我处于“修改模式” )。

如何做到这一点?在哪里?在视图中?表格?

【问题讨论】:

    标签: django forms validation dynamic


    【解决方案1】:

    我建议您覆盖表单的clean() 方法,因为您需要一次访问多个字段。 向字段添加验证更容易,因为您可以从对象的 self.cleaned_data 字典中访问已清理的值,因此我建议您让 both 字段(如果存在)通过,然后根据情况提出您认为合适的异常/修改数据。相关文档为here

    例子:

    class YourForm(forms.Form):
        # Everything as before.
        ...
    
        def clean(self):
            cleaned_data = super(YourForm, self).clean()
            add_attribute = cleaned_data.get("add_attribute")
            modify_attribute = cleaned_data.get("modify_attribute")
    
            if modify_attribute and add_attribute:
                raise forms.ValidationError("You can't add and
                                         modify a product at the same   time.")
    
            if not modify_attribue and not add_attribute:
                raise forms.ValidationError("You must either add or modify a product.")
             # Always return the full collection of cleaned data.
            return cleaned_data
    

    然后在您看来,如果 modify_attribute 可以做一件事,如果 add_attribute 可以做另一件事,因为现在您知道其中只有一个存在。

    【讨论】:

    • 您的解决方案是否从验证中排除任何字段?
    • 这取决于这些字段的定义方式以及“排除验证”的含义。如果这两个字段都用null=True, blank=True 定义,那么我的解决方案将验证这两个字段中只有一个存在。如果两个字段都没有null=True, blank=True,那么我的解决方案将不起作用。当我说向字段添加验证比删除它更容易时,这就是我的意思,所以我建议您将这两个字段都设为可选。
    • 好的,谢谢,我更喜欢寻找其他解决方案,我不希望我的字段是可选的。
    【解决方案2】:

    您可以删除表单__init__ 方法中的字段,对于ModelForm 它看起来像:

    class AddModifyForm(forms.ModelForm):
    
        def __init__(self, *args, **kwargs):
            super(AddModifyForm, self).__init__(*args, **kwargs)
            if self.instance.pk:
                del self.fields['modifyAttribute']
            else:
                del self.fields['addAttribute']
    
        class Meta:
            model = YourModel
            fields = ['addAttribute', 'modifyAttribute', ...]
    

    【讨论】:

    • 是什么意思?在我看来,我使用 来了解表单何时处于“修改模式”。我可以在init函数中使用它吗?可以传递modif=yes或no之类的参数吗?
    【解决方案3】:

    这可能不是完美的解决方案,但我最终设计了 3 种形式:一种用于公共字段,一种用于添加字段,一种用于修改字段。在我看来,我总是一次调用 2 个表单,并且只需要验证这 2 个。

    【讨论】:

      猜你喜欢
      • 2018-11-08
      • 2018-10-10
      • 1970-01-01
      • 2015-06-30
      • 2014-06-14
      • 2020-11-27
      • 1970-01-01
      • 2023-03-15
      • 2011-10-17
      相关资源
      最近更新 更多