2010-10-04 66 views
6

请参阅下面的代码。基本上,当用户创建这个类的对象时,他们需要指定value_type。如果value_type==2(百分比),然后percentage_calculated_on(这是一个CheckboxSelectMultiple在表单/模板端需要有一个或多个项目检查。模型验证不允许我像我试图验证 - 它基本上抛出一个例外,它告诉我,在使用多对多关系之前,实例需要有一个主键值,但是我需要在保存之前先验证对象,我已经在form(modelform)一侧(使用形式的清洁方法),但同样的事情发生也有。django manytomany验证

如何去实现这个验证?

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.") 
+0

我已将Manoj Govindan的答案标记为“接受”,因为它解决了问题。不过,我仍然希望使用Django的模型验证进行验证。所以如果有人有任何想法,请尽力在此发布。谢谢。 – chefsmart 2010-10-04 12:53:43

+0

同样的问题:http://stackoverflow.com/questions/7986510/django-manytomany-model-validation – user920391 2013-02-08 16:02:59

回答

2

我在幻灯的一个测试你的代码cts的管理员应用程序。我能够使用自定义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为你做的)许多代表对许多关系。我相信这应该不重要。

+0

Errr ...是'模型'真的是'admin.ModelAdmin'的一个属性? – 2010-10-04 09:31:39

+0

@ Dominic:这当然不是:P谢谢你指出。我修复了它。 – 2010-10-04 09:34:24

+0

我在我的ModelForm中做类似的事情,除非我先调用super(MyPayableForm,self).clean(),而我使用self.instance.value_type和self.instance.percentage_calculated_on来代替。 – chefsmart 2010-10-04 09:42:41