Home > Blockchain >  Django Forms Validation Check is not working
Django Forms Validation Check is not working

Time:06-22

I am giving this validation rule in my django forms, so when the field is none then it will rasie validation error but validationcoming ervey time , i meant when is none or not none i am getting the validationerror every time, How i solve this issue. models.py

class Check(models.Model):
  use_for_car = models.BooleanField(default=False)

Forms.py

class CheckForm(forms.ModelForm):
    translated_names = TranslationField()

    def clean(self):
        cleaned_data = super(CheckForm, self).clean()
        use_for_car = self.cleaned_data.get("use_for_car")
        
        if use_for_car is None:  
            raise ValidationError("Use For Car NEED TO BE FILLED ")
        return use_for_registrations

    class Meta:
        fields = "__all__"
        model = models.Check

CodePudding user response:

This is already the case, since you did not specify blank=True [Django-doc], this means that the form field is required, so this means that for the form field, required=True [Django-doc], and for a BooleanField form field [Django-doc], this means:

Since all Field subclasses have required=True by default, the validation condition here is important. If you want to include a boolean in your form that can be either True or False (e.g. a checked or unchecked checkbox), you must remember to pass in required=False when creating the BooleanField.

You thus can simply let Django do the work:

class CheckForm(forms.ModelForm):
    translated_names = TranslationField()

    # no clean override

    class Meta:
        model = models.Check
        fields = '__all__'
  • Related