Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 77 ยท Forms

Form Validation

Write your own Django form validation with validators, clean_<field> methods, clean() for cross-field rules, ValidationError codes and add_error.

Field types such as EmailField or IntegerField(min_value=13) cover the common rules. Real applications have more: usernames that must be unique or must not be reserved, an end date that must come after the start date, a password that must match its confirmation, a promo code with a special format. Django gives you four places to put such rules, and knowing which one to use makes your forms short and predictable.

This lesson builds on Django Forms. You will learn the order in which Django validates a form, write reusable validators, add per-field cleaning with clean_<field>(), check several fields together in clean(), and raise errors that are easy to test thanks to error codes.

The validation pipeline

When you call is_valid() (or access errors), Django runs full_clean(), which does three steps in this order:

flowchart TB
    A["1. Each field: to_python() and validate()<br/>(type conversion, required, choices)"] --> B["2. Each field: its validators<br/>(max_length, RegexValidator, yours)"]
    B --> C["3. clean_fieldname() for that field"]
    C --> D["4. Form.clean()<br/>(rules across fields)"]
    D --> E{"errors?"}
    E -->|"none"| F["cleaned_data is complete"]
    E -->|"some"| G["errors filled; failed fields<br/>removed from cleaned_data"]

Steps 1 to 3 run per field in declaration order; the form-wide clean() runs last, after every field has been processed.

Two consequences follow. First, a field that fails an early step is skipped by later steps, so clean_<field>() only runs when the field value is already a valid Python object. Second, by the time clean() runs, cleaned_data may be missing fields that failed, so you must use .get() there.

Validators

A validator is any callable that takes a value and raises ValidationError if it is not acceptable. Django ships many (RegexValidator, MinLengthValidator, MaxValueValidator, validate_email, ...) and you can write your own as a plain function. Because validators are independent of forms, you can reuse the same function on form fields and on model fields.

The ValidationError constructor takes three arguments worth knowing: the message, a short machine-readable code, and params that fill %(name)s placeholders in the message. The next example combines two validators with clean_username() and custom error_messages.

Python Validators, clean_username and custom messages

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

What happened:

  • The three failures were reported together. Django does not stop at the first bad field, so the user sees every problem at once.
  • A code travels with each message (bad_format, odd, reserved). Codes let tests and code assert on the kind of problem without depending on wording that may change or be translated.
  • params filled %(value)s and %(name)s. Always pass values through params instead of formatting the string yourself. This keeps messages translatable and lets Django escape them safely.
  • error_messages on a field overrides messages for specific built-in codes such as required and invalid.
  • clean_username() must return the cleaned value. Forgetting the return is the classic mistake: the field silently becomes None.

Where clean_<field> fits

Use a validator when the rule is generic and reusable (format, range, a blocklist used in several forms). Use clean_<field>() when the rule needs the form instance, for example to look at self.user, or when you also want to normalize the value, as with strip().lower() above. The method name is clean_ plus the field name, and it runs after the field's own validation succeeded.

To check uniqueness of a username or email, query the database inside clean_<field>() (or rely on unique=True in a ModelForm). Remember that a check in the form is a convenience for the user; only a database constraint guarantees uniqueness when two requests arrive at the same time.

Rules across fields: clean()

Some rules involve more than one field. The end date must come after the start date. The password and its confirmation must match. For these, override clean(). It runs after all individual fields, calls super().clean() to get cleaned_data, and can raise errors in two ways:

  • raise ValidationError(...) reports a non-field error, shown at the top of the form (stored under the key __all__).
  • self.add_error("field", "message") attaches the error to a specific field, and removes that field from cleaned_data.
Python Cross-field rules with clean() and add_error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice three things in the output:

  1. The error for end was added with add_error, so it appears next to the field, while the password mismatch is a form-level error under __all__. Where an error belongs decides where the user sees it: put it on the field the user must change whenever you can.
  2. After add_error("end", ...), the end key is gone from cleaned_data. Anything that reads cleaned_data["end"] later must tolerate that.
  3. The third form is missing start. Django still calls clean(), which is why we read values with .get(): otherwise a KeyError would turn a mere validation problem into a server error (HTTP 500).

The error codes line shows that a plain string given to add_error has no code (None). Pass a ValidationError("...", code="...") instead when you want one.

You may also pass a dictionary to ValidationError to target several fields at once: raise ValidationError({"end": "Too early", "start": "Too late"}).

Several errors from one rule

A validator or clean method can report more than one problem by raising a list of ValidationError instances. Django also runs all validators of a field and gathers their errors, so a password field can list every unmet requirement instead of just the first.

Python Collecting several errors and reading codes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

All three validators ran for "abc", so the user sees every unmet rule at once. When the error list is used in a template, {{ form.password.errors }} renders a <ul class="errorlist"> that you can style. add_error is also handy in views: after a form passes its own validation, a view can still add an error because of something only the view knows (a breached password lookup, a rate limit, a failed API call) and re-render the form.

Validating URLs

Two tools check web addresses. URLField is the form field: it strips spaces, runs the URL validator and returns a clean string. URLValidator is the validator behind it, and you can attach it to any other field or call it directly. Its schemes argument limits which protocols are accepted (the defaults are http, https, ftp and ftps), and message and code customize the error like for every validator.

Since Django 5.0, URLField(assume_scheme="https") prepends a scheme when the user types example.com/docs, so you do not have to reject addresses that people naturally write without https://.

Python URLValidator and URLField

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The validator only checks the shape of the address: https://localhost passes, and nothing proves that the page exists. To check that a link works you would have to request it from your server, which is slow and raises security questions (see security). Validate the shape in the form and treat reachability as a separate, asynchronous job.

Practical advice

  • Put the rule in the narrowest place. A reusable format check belongs in a validator, a normalization or request-dependent rule in clean_<field>(), a relation between fields in clean().
  • Always give errors a code. Tests, logging and translations all benefit.
  • Never trust the browser. required, min and maxlength attributes are conveniences; Django re-checks everything on the server.
  • Keep validation free of side effects. Do not save data inside clean(); it can run multiple times and may fail later.
  • Guard clean() with .get(). Fields that failed are missing from cleaned_data.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In which order does Django validate a form?

    Every field is processed in declaration order (conversion, validators, then its clean_<field> method); the form-wide clean() runs last, after all fields.
  2. 2. What is the most common bug in a clean_<field>() method?

    clean_<field>() must return the value that should end up in cleaned_data. Without a return statement the value becomes None.
  3. 3. How do you attach an error to the end field from inside clean()?

    add_error attaches the error to the named field and removes it from cleaned_data. A plain raise inside clean() creates a non-field error.
  4. 4. Why should you read values with cleaned_data.get("start") inside clean()?

    clean() runs even when some fields failed. Those fields are not in cleaned_data, so indexing with brackets could raise KeyError.
  5. 5. What is the benefit of giving a ValidationError a code?

    Codes are stable identifiers. Messages can change or be translated, but a test that checks code == "too_short" keeps working.

Summary

  • Validation order: field conversion, field validators, clean_<field>(), then Form.clean().
  • A validator is a callable that raises ValidationError; reuse it on forms and models.
  • Pass code and params to ValidationError; use error_messages to customize built-in messages.
  • clean_<field>() normalizes and checks one field and must return the value.
  • clean() handles rules across fields: raise for non-field errors, use add_error("field", ...) for field errors, and read data with .get().
  • add_error also works after validation, for example from a view.
  • The browser's checks are only conveniences; the server always validates.

Next, let Django generate forms from your models in ModelForms.