gpt4 book ai didi

python - 基于同一模型中其他字段的django字段验证器

转载 作者:行者123 更新时间:2023-12-05 07:59:39 25 4
gpt4 key购买 nike

我有这个模型

class Env(models.Model):    
functional_count = models.PositiveIntegerField()
current_count = models.PositiveIntegerField()

现在我希望 functional_count 始终小于 current_count
所以在创建过程中,

def form_valid(self, form):    
form.instance.current_count = 0

这是因为我在初始化期间想要 current_count。然后我的 python 代码永远不允许 current_count 超过 functional_count

问题出在更新中。

class EnvUpdate(UpdateView):  
model = Capacity.models.Envapps
fields = ['functional_count']
template_name_suffix = '_update_form'

那么我是否包含一个验证器?如果是,在哪里以及如何?
或者其他选项是在 get_success_url() 中验证。
还有其他解决方案吗?

最佳答案

假设您的更新是通过表单进行的(如使用 form_valid() 所建议的那样,也许您可​​以使用表单 clean() 方法,如 the documentation 中所述。这允许您对依赖于彼此。该文档还有一个示例,可以让您更进一步。

更新

根据您的评论,我了解到您尝试使用 clean()里面EnvUpdate , 它继承自基于类的 UpdateView看法。通过 UpdateView 提供的所有 mixins显然不提供 clean()方法,所以你不能覆盖它。

我实际上指的是 clean()在表单类中(如下链接所示)。所以,看起来您需要创建自己的 ModelForm 类,例如:

class EnvappsForm(forms.ModelForm):
class Meta:
model = Capacity.models.Envapps
fields = ['functional_count']

def clean(self):
cleaned_data = super(ContactForm, self).clean()
if cleaned_data['functional_count'] >= form.instance.current_count:
raise ValidationError('too large')
return cleaned_data

然后在你看来:

class EnvUpdate(UpdateView):
model = Capacity.models.Envapps
template_name_suffix = '_update_form'
form_class = EnvappsForm

注意:这是完全未经测试的!不知道clean()里面的对比是否有效(即,如果可以找到 form.instance.current_count),以及是否 EnvUpdate将覆盖 form_class (它不应该,但我从未尝试过)。 可能您甚至有可能删除 meta子类,并提供 modelfields来自 EnvUpdate ,正如您在上面所做的那样。这只是您可以轻松尝试的东西。

关于python - 基于同一模型中其他字段的django字段验证器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20991449/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com