Django Tutorial

Django Create A Complete Project

Django Template

Django Database Query

Django Form

Django Authentication and Permission Management

Django unittest

Django Advanced

Django Form Custom Validation Rules

Django provides multiple ways to add custom validation rules to form fields. In this tutorial, we will cover three different methods to apply custom validation:

  1. Custom field validation method
  2. Custom form validation method
  3. Custom form-wide validation method (cleaning and validating the whole form)

Let's assume we're working on a registration form with three fields: username, email, and password. We will use these fields as examples in our custom validation rules.

1. Custom field validation method

To add a custom validation method for a specific field, you can define a method in your form class named clean_<fieldname>.

Example: Add custom validation for the username field.

In your app's forms.py file:

from django import forms
from django.contrib.auth.models import User

class RegistrationForm(forms.Form):
    username = forms.CharField(max_length=100)
    email = forms.EmailField()
    password = forms.CharField(widget=forms.PasswordInput)

    def clean_username(self):
        username = self.cleaned_data['username']
        if User.objects.filter(username=username).exists():
            raise forms.ValidationError('Username already exists.')
        return username

In this example, we added the clean_username method to check if the entered username already exists in the User model.

2. Custom form validation method

You can also create a custom validation method that checks the values of multiple fields.

Example: Ensure the email domain is from a specific organization.

In your app's forms.py file:

class RegistrationForm(forms.Form):
    # ...

    def clean_email(self):
        email = self.cleaned_data['email']
        domain = email.split('@')[-1]
        if domain != 'example.com':
            raise forms.ValidationError('Please use an email address with the example.com domain.')
        return email

In this example, we added the clean_email method to ensure that the email address's domain is example.com.

3. Custom form-wide validation method (cleaning and validating the whole form)

To create a custom form-wide validation method, you need to override the form's clean method. This method is called after all individual field validations.

Example: Ensure that the password is not a common word.

In your app's forms.py file:

class RegistrationForm(forms.Form):
    # ...

    def clean(self):
        cleaned_data = super().clean()

        password = cleaned_data.get('password')
        common_passwords = ['password', '123456', 'qwerty']

        if password and password.lower() in common_passwords:
            raise forms.ValidationError('Please choose a more secure password.')

        return cleaned_data

In this example, we override the clean method to ensure that the entered password is not a common word.

These are the three different ways you can add custom validation rules in Django forms. Depending on your use case and the scope of the validation, you can choose the appropriate method to implement your custom validation rules.

  1. Adding custom validation rules in Django forms:

    • Description: Enhance Django forms by adding custom validation rules to ensure data integrity and user input correctness.
    • Code Example:
      # forms.py in your app
      from django import forms
      
      class MyForm(forms.Form):
          def clean_custom_field(self):
              # Custom validation logic for 'custom_field'
              data = self.cleaned_data['custom_field']
              if not condition_met(data):
                  raise forms.ValidationError('Invalid input for custom field.')
              return data
      
  2. Creating custom validators for Django forms:

    • Description: Create reusable custom validators in Django forms to enforce specific validation rules across multiple forms.
    • Code Example:
      # validators.py in your app
      from django.core.exceptions import ValidationError
      
      def validate_even(value):
          if value % 2 != 0:
              raise ValidationError('Enter an even number.')
      
  3. Django form clean methods for custom validation:

    • Description: Utilize the clean_<field_name> method in Django forms to implement custom validation for specific form fields.
    • Code Example:
      # forms.py in your app
      from django import forms
      
      class MyForm(forms.Form):
          def clean_custom_field(self):
              # Custom validation logic for 'custom_field'
              data = self.cleaned_data['custom_field']
              # ... (additional validation)
              return data
      
  4. Handling custom error messages in Django forms:

    • Description: Customize error messages for custom validation rules in Django forms to provide informative feedback to users.
    • Code Example:
      # forms.py in your app
      from django import forms
      
      class MyForm(forms.Form):
          def clean_custom_field(self):
              data = self.cleaned_data['custom_field']
              if not condition_met(data):
                  raise forms.ValidationError('Invalid input for custom field. Must satisfy specific condition.')
              return data
      
  5. Django custom validation for CharField:

    • Description: Implement custom validation for a CharField in Django forms to validate string inputs.
    • Code Example:
      # forms.py in your app
      from django import forms
      
      class MyForm(forms.Form):
          def clean_name(self):
              name = self.cleaned_data['name']
              if len(name) < 3:
                  raise forms.ValidationError('Name must be at least 3 characters long.')
              return name
      
  6. Custom validation for DateField in Django forms:

    • Description: Create custom validation for a DateField in Django forms to validate date inputs.
    • Code Example:
      # forms.py in your app
      from django import forms
      
      class MyForm(forms.Form):
          def clean_birthdate(self):
              birthdate = self.cleaned_data['birthdate']
              if birthdate > timezone.now().date():
                  raise forms.ValidationError('Birthdate cannot be in the future.')
              return birthdate
      
  7. Django custom validation for EmailField:

    • Description: Implement custom validation for an EmailField in Django forms to enforce email format rules.
    • Code Example:
      # forms.py in your app
      from django import forms
      
      class MyForm(forms.Form):
          def clean_email(self):
              email = self.cleaned_data['email']
              if not is_valid_email(email):
                  raise forms.ValidationError('Enter a valid email address.')
              return email
      
  8. Implementing custom validation for URLField in Django forms:

    • Description: Create custom validation for a URLField in Django forms to validate URL inputs.
    • Code Example:
      # forms.py in your app
      from django import forms
      
      class MyForm(forms.Form):
          def clean_website_url(self):
              url = self.cleaned_data['website_url']
              if not is_valid_url(url):
                  raise forms.ValidationError('Enter a valid URL.')
              return url
      
  9. Django custom validation for BooleanField:

    • Description: Implement custom validation for a BooleanField in Django forms to enforce specific rules for boolean inputs.
    • Code Example:
      # forms.py in your app
      from django import forms
      
      class MyForm(forms.Form):
          def clean_agree_terms(self):
              agree_terms = self.cleaned_data['agree_terms']
              if not agree_terms:
                  raise forms.ValidationError('You must agree to the terms.')
              return agree_terms
      
  10. Django formsets with custom validation:

    • Description: Apply custom validation to Django formsets to ensure consistency and validity across multiple forms.
    • Code Example:
      # forms.py in your app
      from django import forms
      
      class MyForm(forms.Form):
          # ... (form fields)
      
      MyFormSet = forms.formset_factory(MyForm, extra=2)
      
  11. Django custom validation for ModelForm:

    • Description: Implement custom validation for a ModelForm in Django to validate model instances before saving.
    • Code Example:
      # forms.py in your app
      from django import forms
      from .models import MyModel
      
      class MyModelForm(forms.ModelForm):
          class Meta:
              model = MyModel
      
          def clean(self):
              cleaned_data = super().clean()
              # Custom model form validation logic
              return cleaned_data
      
  12. Conditional validation in Django forms:

    • Description: Apply conditional validation to Django forms based on specific criteria, enabling dynamic validation rules.
    • Code Example:
      # forms.py in your app
      from django import forms
      
      class MyForm(forms.Form):
          def clean(self):
              cleaned_data = super().clean()
              if cleaned_data.get('condition_met'):
                  # Custom validation logic based on a condition
                  # ...
              return cleaned_data
      
  13. Django form clean and custom error handling:

    • Description: Implement custom error handling in Django forms, leveraging the clean method for comprehensive validation.
    • Code Example:
      # forms.py in your app
      from django import forms
      
      class MyForm(forms.Form):
          def clean(self):
              cleaned_data = super().clean()
              # Custom error handling logic
              if not condition_met(cleaned_data):
                  raise forms.ValidationError('Invalid input based on custom condition.')
              return cleaned_data
      
  14. Handling file upload validation in Django forms:

    • Description: Implement custom validation for file uploads in Django forms, ensuring proper file types, sizes, etc.
    • Code Example:
      # forms.py in your app
      from django import forms
      
      class MyFileForm(forms.Form):
          def clean_file(self):
              file = self.cleaned_data['file']
              # Custom file validation logic
              return file