Django - How to specify which field a validation fails on?

后端 未结 6 1359
太阳男子
太阳男子 2021-01-31 01:43

I have this model I\'m showing in the admin page:

class Dog(models.Model):
    bark_volume = models.DecimalField(...
    unladen_speed = models.DecimalField(...
         


        
6条回答
  •  时光说笑
    2021-01-31 02:24

    Use a clean_ method that is specific to the field:

    class DogForm(forms.ModelForm):
        class Meta:
            model = Dog
    
        def clean_bark_volume(self):
            if self.cleaned_data['bark_volume'] < 5:
                raise ValidationError("must be louder!")
    

    See the clean part of the Form Validation page. Also, make sure to use cleaned_data instead of the form field itself; the latter may have old data. Finally, do this on the form and not the model.

提交回复
热议问题