Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you want to validate a certain field depending on the values of other fields, you need to to it at the form level and overwrite the field's <code>clean</code> method. <a href="https://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other" rel="nofollow">Here's the docs on the subject</a> - they are very good. </p> <pre><code>class CustomForm(forms.Form): custom_field = CustomField() def clean(self): cleaned_data = super(CustomForm, self).clean() custom_field = cleaned_data.get("custom_field") ... </code></pre> <p><a href="https://docs.djangoproject.com/en/dev/ref/forms/validation/#form-and-field-validation" rel="nofollow">If you look at the flow of how forms are validated</a>, you will see that the <strike><code>clean</code> method is run if all the other fields validate independently, so at this stage, the form can be considered valid:</strike> </p> <blockquote> <p>These methods are run in the order given above, one field at a time. That is, for each field in the form (in the order they are declared in the form definition), the <code>Field.clean()</code> method (or its override) is run, then <code>clean_&lt;fieldname&gt;()</code>. Finally, once those two methods are run for every field, the <code>Form.clean()</code> method, or its override, is executed.</p> </blockquote> <p>The final clean method is actually run regardless of if there's an error so you have to iterate through the <code>cleaned_data</code> to make sure there are no errors</p> <blockquote> <p>The clean() method for the Form class or subclass is always run. If that method raises a ValidationError, cleaned_data will be an empty dictionary.</p> <p>The previous paragraph means that if you are overriding Form.clean(), you should iterate through self.cleaned_data.items(), possibly considering the _errors dictionary attribute on the form as well. In this way, you will already know which fields have passed their individual validation requirements.</p> </blockquote>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload