Skip to content Skip to sidebar Skip to footer

Raise Form Error Below The Input Field In Case Any Invalid Data Is Entered In Django

I am using pre_save to raise error if while entering the data any condition is not met. But when I am using raise ValidationError(). Its showing me error in the next page like this

Solution 1:

You should use clean method for this.

defclean(self):
    ifstr(self.emp_name) == "BB":
        raise ValidationError('Manager already assigned to this department')

This method is called before saving the object. The clean() method on a Field subclass is responsible for running to_python(), validate(), and run_validators() in the correct order and propagating their errors.

Solution 2:

You can respective validation in modelField as a function reference in argument validators

def check_dept_has_manager(value):
     ifvalue== "BB":
        raise ValidationError("Manager already assigned to this department")else:
        return value

In your model

classWorks_in(models.Model):
      emp_name = models.CharField(max_length=2,validators=[check_dept_has_manager])

If you hit save it will show validation on field

Post a Comment for "Raise Form Error Below The Input Field In Case Any Invalid Data Is Entered In Django"