How to do model level custom field validation in django?

末鹿安然 提交于 2019-12-14 03:58:07

问题


I have this model:

class StudentIelts(Model):

    SCORE_CHOICES = [(i/2, i/2) for i in range(0, 19)]

    student = OneToOneField(Student, on_delete=CASCADE)
    has_ielts = BooleanField(default=False,)
    ielts_listening = FloatField(choices=SCORE_CHOICES, null=True, blank=True, )
    ielts_reading = FloatField(choices=SCORE_CHOICES, null=True, blank=True, )
    ielts_writing = FloatField(choices=SCORE_CHOICES, null=True, blank=True, )
    ielts_speaking = FloatField(choices=SCORE_CHOICES, null=True, blank=True, )

and have this model form:

class StudentIeltsForm(ModelForm):

    class Meta:
        model = StudentIelts
        exclude = ('student')

    def clean(self):
        cleaned_data = super().clean()
        has_ielts = cleaned_data.get("has_ielts")

        if has_ielts:
            msg = "Please enter your score."
            for field in self.fields:
                if not self.cleaned_data.get(str(field)):
                    self.add_error(str(field), msg)

        else:
            for field in self.fields:
                self.cleaned_data[str(field)] = None
                self.cleaned_data['has_ielts'] = False

        return cleaned_data

As you see, if a student has ielts, then he/she has to specify his/her scores in the model form. I now want to do this on the model level. So I need to customize my model save method, or clean method or full_clean method, I am not sure, I guess.

How should I do this?

Will my StudentIeltsForm behavior be the same as before if I change it as below?

class StudentIeltsForm(ModelForm):

    class Meta:
        model = StudentIelts
        exclude = ('student')

I read this: https://docs.djangoproject.com/en/2.2/ref/models/instances/#validating-objects

and this: https://kite.com/python/docs/django.db.models.Model.clean

and I know that to iterate over model field I have to use

for field in self._meta.fields:

But I have not yet reached to the solution to this question.

来源:https://stackoverflow.com/questions/58183474/how-to-do-model-level-custom-field-validation-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!