【问题标题】:Django Admin: Making mandatory fields non-mandatory dynamicallyDjango Admin:动态地使必填字段成为非必填项
【发布时间】:2010-11-27 06:55:24
【问题描述】:

当另一个[关联]字段具有特定值时,如何使必填字段变为非必填?

假设我有以下模型:

class foo(models.Model):
    bar = models.CharField(max_length=200)
    foo_date = models.DateTimeField()

当我保存并且 bar 包含某个值时,我希望 foo_date 成为非强制性的。我该如何做到这一点?谢谢。

【问题讨论】:

    标签: django dynamic field admin


    【解决方案1】:

    T.Stone 是对的。这就是您使用模型表单的方式:

    class foo(models.Model):
        bar = models.CharField(max_length=200)
        foo_date = models.DateTimeField()
    
    class ClientAdmin( MyModelAdmin ):
        form = FooModelForm
    
    class FooModelForm( forms.ModelForm ):
    
        def clean(self):
            cleaned_data = self.cleaned_data
            if cleaned_data.get("bar") == 'some_val' and not cleaned_data.get('foo_date'):
                msg = 'Field Foo Date is mandatory when bar is some_val'
                self._errors[field] = ErrorList([msg])
                del cleaned_data[field]
            return cleaned_data
    

    http://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other

    【讨论】:

      【解决方案2】:

      我认为只需将 foo_barr 设置为 blank=True,然后实现您自己的表单和自定义验证以供 Admin 模型使用。请参阅文档的这一部分——Adding custom validation to admin

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-04-18
        • 2018-06-12
        • 2023-04-01
        • 2018-01-07
        • 1970-01-01
        • 1970-01-01
        • 2019-08-23
        • 1970-01-01
        相关资源
        最近更新 更多