0

モデルの clean() メソッドのフィールドの「必須」プロパティを変更したいと考えています。

これが私のモデルです:

class SomeModel(models.Model):
    type = models.CharField()
    attr1 = models.ForeignKey(Attr1, blank=True, null=True)
    attrs2 = models.ForeignKey(Attr2, blank=True, null=True)

__init__現在、ビューから新しいパラメーターを追加して、ModelForm でこれを行っています。フィールドの必須を動的に設定します。

私のモデルで同じことを達成できますか? 私はAPIにdjango-rest-frameworkを使用しています(ModelFormを使用しています)ので、 (とfull_clean()を含む)が実行されます。clean_fields()clean()

type が何らかの文字列で始まる場合、attr1/attr2 フ​​ィールドが必要だとします。

このチェックインを実行できることはわかっていますが、Model.clean()その時点で着陸しNON_FIELD_ERRORSます。

def clean(self):
    if self.type.startswith("somestring"):
        if self.attr1 is None and self.attr2 is None:
            raise ValidationError("attr1 and attr2 are required..")

attr1 および attr2 フ​​ィールド エラーに関連付けられたこれらのエラーを、単純な「このフィールドは必須です」(標準の「必須」django エラー) で表示したいと思います。

4

1 に答える 1

0

これは私にとってうまくいくコード例です:

def clean(self):
        is_current = self.cleaned_data.get('is_current',False)
        if not is_current:
            start_date = self.cleaned_data.get('start_date', False)
            end_date   = self.cleaned_data.get('end_date', False)
            if start_date and end_date and start_date >= end_date:
                self._errors['start_date'] = ValidationError(_('Start date should be before end date.')).messages
        else:
            self.cleaned_data['end_date']=None
        return self.cleaned_data
于 2013-05-20T14:29:14.290 に答える