6

以下のコードをご覧ください。基本的に、ユーザーがこのクラスのオブジェクトを作成するときは、を指定する必要がありますvalue_type。If value_type==2(percentage)、then percentage_calculated_on(これは、フォーム/テンプレート側のCheckboxSelectMultipleで、1つ以上の項目をチェックする必要があります。モデルの検証では、私が試みているように検証できません。基本的に、次のような例外がスローされます。多対多の関係を使用するには、インスタンスに主キー値が必要であるとのことですが、保存する前にまずオブジェクトを検証する必要があります。この検証をフォーム(モデルフォーム)側で試しました(フォームのクリーンな方法)ですが、同じことがそこでも起こります。

この検証を達成するにはどうすればよいですか?

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.")
4

1 に答える 1

2

プロジェクトの管理アプリの1つでコードをテストしました。カスタムを使用して、必要な検証を実行できました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しかし、これは問題ではないと思います。

于 2010-10-04T09:28:56.493 に答える