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

后端 未结 6 1384
太阳男子
太阳男子 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:36

    To note for anyone that may come across this with a newer version of Django - the clean_fields method from the accepted answer now requires an "exclude" param. Also - I believe the accepted answer is also missing a call to it's super function. The final code that I used was:

    def clean_fields(self, exclude=None):
        super(Model, self).clean_fields(exclude)
    
        if self.field_name and not self.field_name_required:
            raise ValidationError({'field_name_required':["You selected a field, so field_name_required is required"]})
    

提交回复
热议问题