Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django overwrite form clean method

When overwriting a form clean method how do you know if its failed validation on any of the fields? e.g. in the form below if I overwrite the clean method how do I know if the form has failed validation on any of the fields?

class PersonForm(forms.Form):
    title = Forms.CharField(max_length=100)
    first_name = Forms.CharField(max_length=100)
    surname = Forms.CharField(max_length=100)
    password = Forms.CharField(max_length=100)

def clean(self, value):
    cleaned_data = self.cleaned_data

    IF THE FORM HAS FAILED VALIDATION:
        self.data['password'] = 'abc'
        raise forms.ValidationError("You have failed validation!")
    ELSE:
        return cleaned_data 

Thanks

like image 243
John Avatar asked Mar 12 '10 12:03

John


People also ask

What is clean method in Django?

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. If, at any time, any of the methods raise ValidationError , the validation stops and that error is raised.

How do you exclude a specific field from a ModelForm?

Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.

What is ModelForm in Django?

Django Model Form It is a class which is used to create an HTML form by using the Model. It is an efficient way to create a form without writing HTML code. Django automatically does it for us to reduce the application development time.

How do you remove this field is required Django?

If yes try to disable this behavior, set the novalidate attribute on the form tag As <form action="{% url 'new_page' %}", method="POST" novalidate> in your html file.


2 Answers

You can check if any errors have been added to the error dict:

def clean(self, value):
    cleaned_data = self.cleaned_data

    if self._errors:
        self.data['password'] = 'abc'
        raise forms.ValidationError("You have failed validation!")
    else:
        return cleaned_data 

BONUS! You can check for errors on specific fields:

def clean(self, value):
    cleaned_data = self.cleaned_data

    if self._errors and 'title' in self._errors:
        raise forms.ValidationError("You call that a title?!")
    else:
        return cleaned_data 
like image 114
Mark Lavin Avatar answered Sep 28 '22 02:09

Mark Lavin


If your data does not validate, your Form instance will not have a cleaned_data attribute

Django Doc on Accessing "clean" data

Use self.is_valid().

like image 25
stefanw Avatar answered Sep 28 '22 00:09

stefanw