VOOZH about

URL: https://www.geeksforgeeks.org/python/python-form-validation-using-django/

⇱ Form Validation in Django - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Form Validation in Django

Last Updated : 7 May, 2026

Form validation ensures that user-submitted data meets specific requirements before being processed or saved. It can be applied to fields such as username, gender, or text inputs to maintain accuracy and consistency. Django simplifies this process by combining form handling and validation logic within its form classes.

Example: Custom Validation with Django Forms

Consider a project named 'geeksforgeeks' having an app named 'geeks'.

Step 1: Create the Model

In geeks/models.py, define a model named Post to store user data:

Step 2: Apply Migrations

After creating this model, two commands need to be run to create the corresponding database tables:

python manage.py makemigrations
python manage.py migrate

Step 3: Create a ModelForm with Validation

Creating a form involves defining validation rules for fields, such as requiring the username to be at least 5 characters and the post text to be at least 10 characters. These rules are implemented in the PostForm class.

In geeks/forms.py, define a form that includes custom validation logic:

Step 4: Define the View

In geeks/views.py, create a view to handle GET and POST requests.

Step 5: Configure URLs

In geeks/urls.py, map the root URL to the home view.

Include app’s URLs in the project-level geeksforgeeks/urls.py:

Step 6: Create the Template

In geeks/templates/home.html, design a simple form using Bootstrap for styling.

Step 7: Run the Server

python manage.py runserver

Visit: http://127.0.0.1:8000/ to view the form in action

👁 Image

If the form is submitted with a username shorter than 5 characters or post text shorter than 10 characters, validation errors are displayed immediately. The form highlights the invalid fields and shows appropriate error messages.

👁 Image

Comment
Article Tags:
Article Tags: