【问题标题】:Using dynamic configurations with modelfield form validation in django在 django 中使用带有 modelfield 表单验证的动态配置
【发布时间】:2018-12-26 15:58:03
【问题描述】:

我已经设置了一个名为 Configuration 的模型,其中包含可配置的详细信息,例如 maximum_stake,并在 admin.py 中注册了它,以便管理员可以即时更改它们。

我的大部分验证都是通过自然的 ModelForm 验证完成的,但是当我尝试使用 Configuration 模型中动态变化的约束来执行此操作时,Postgre 抱怨关系不存在(所以我无法创建迁移来构建或编辑配置模型表)。但是,即使在进行了这些更改之后,数据库仍然不满意。有没有其他方法可以做到这一点?

# models.py

class Investor(models.Model):
    stake = models.DecimalField(max_digits=4, decimal_places=2, default=0.00)

class InvestorForm(forms.ModelForm):
    stake = forms.DecimalField(help_text="The income stake as a percentage (0.00% - 8.00%)", validators=[
        MinValueValidator(0, f'Stake must be between 0.00%% and {getConfig(ConfigData.MAXIMUM_STAKE)}.00%%'),
        MaxValueValidator(getConfig(ConfigData.MAXIMUM_STAKE),
                          f'Stake must be between 0.00%% and {getConfig(ConfigData.MAXIMUM_STAKE)}.00%%')
    ])

    class Meta:
        model = Investor
        fields = '__all__'

【问题讨论】:

    标签: django postgresql validation django-models django-admin


    【解决方案1】:

    您可以在使用动态约束时使用 ModelForm 的 Clean 方法来检查验证:

     def clean(self):
            cleaned_data = super().clean()
            current_stake = cleaned_data.get("stake")
            minimum_stake = 0
            maximum_stake = ConfigData.objects.first().maximum_stake #get the object from database where the configuration is saved dynamically here
    
            if not(current_stake > minimum_stake and current_stake <= maximum_stake):
                # Only do something if both fields are valid so far or raise error
                raise forms.ValidationError(f'Stake must be between {minimum_stake}%% and {maximum_stake}.00%%')
    

    或者您可以创建一个自定义 Django 字段,如下所示:

    from django import forms
    
    class CustomStakeField(forms.Field):
        def to_python(self, value):
            return float(value)
    
        def validate(self, value):
            """Check if value lies within range"""
            super().validate(value)
            minimum_stake = 0
            maximum_stake = ConfigData.objects.first().maximum_stake #get the object from database where the configuration is saved dynamically here
    
                if not(current_stake > minimum_stake and current_stake <= maximum_stake):
                    # Only do something if both fields are valid so far or raise error
                    raise forms.ValidationError(f'Stake must be between {minimum_stake}%% and {maximum_stake}.00%%')
    

    然后在模型表单中简单地使用它:

    stake = CustomStakeField()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-05
      • 2015-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-30
      • 1970-01-01
      相关资源
      最近更新 更多