gpt4 book ai didi

Django 多对多验证

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

请参阅下面的代码。基本上,当用户创建此类的对象时,他们需要指定value_type。如果 value_type==2 (百分比),则 percentage_calculated_on (表单/模板端的 CheckboxSelectMultiple)需要检查一个或多个项目。模型验证是'它不允许我像我尝试的那样进行验证——它基本上会抛出一个异常,告诉我在可以使用多对多关系之前,实例需要有一个主键值。但我需要首先验证对象之前保存它。我已经在表单(modelform)端尝试过这种验证(使用表单的 clean 方法),但同样的事情也发生在那里。

我该如何实现此验证?

INHERENT_TYPE_CHOICES = ((1, 'Payable'), (2, 'Deductible'))
VALUE_TYPE_CHOICES = ((1, 'Amount'), (2, 'Percentage'))

class Payable(models.Model):
name = models.CharField()
short_name = models.CharField()
inherent_type = models.PositiveSmallIntegerField(choices=INHERENT_TYPE_CHOICES)
value = models.DecimalField(max_digits=12,decimal_places=2)
value_type = models.PositiveSmallIntegerField(choices=VALUE_TYPE_CHOICES)
percentage_calculated_on = models.ManyToManyField('self', symmetrical=False)

def clean(self):
from django.core.exceptions import ValidationError
if self.value_type == 2 and not self.percentage_calculated_on:
raise ValidationError("If this is a percentage, please specify on what payables/deductibles this percentage should be calculated on.")

最佳答案

我在我的一个项目的管理应用程序中测试了您的代码。我能够使用自定义 ModelForm 执行您所需的验证。见下文。

# forms.py
class MyPayableForm(forms.ModelForm):
class Meta:
model = Payable

def clean(self):
super(MyPayableForm, self).clean() # Thanks, @chefsmart
value_type = self.cleaned_data.get('value_type', None)
percentage_calculated_on = self.cleaned_data.get(
'percentage_calculated_on', None)
if value_type == 2 and not percentage_calculated_on:
message = "Please specify on what payables/deductibles ..."
raise forms.ValidationError(message)
return self.cleaned_data

# admin.py
class PayableAdmin(admin.ModelAdmin):
form = MyPayableForm

admin.site.register(Payable, PayableAdmin)

管理应用使用 SelectMultiple 小部件(而不是像您那样使用 CheckboxSelectMultiple)来表示多对多关系。我相信这应该不重要。

关于Django 多对多验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3853657/

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