← Back to Django Course | Chapter 7: Django Forms | Lesson 10 of 11

Custom Form का Validation

Custom validation आपके form को एक special rule सिखाना है जो built-in checks को already नहीं पता, जैसे 'password में एक number होना चाहिए'।
Syntax
markup
class FormName(forms.Form):
    field_name = forms.CharField()

    def clean_field_name(self):
        value = self.cleaned_data['field_name']
        if invalid:
            raise ValidationError('message')
        return value

    def clean(self):
        cleaned = super().clean()
        # compare several fields
        return cleaned

एक Single Field Validate करना

एक method जिसका नाम clean_<fieldname> है is_valid() के दौरान अपने आप run होता है और उसे field की cleaned value return करनी चाहिए।

उदाहरण: Validating a Single Field

A method named clean_<fieldname> runs automatically during is_valid() and must return the field's cleaned value.

markup
from django.core.exceptions import ValidationError


class SignupForm(forms.Form):
    username = forms.CharField(max_length=50)

    def clean_username(self):
        username = self.cleaned_data['username']
        if ' ' in username:
            raise ValidationError('Username cannot contain spaces.')
        return username
{# Django-only code -- models.py/views.py/urls.py/settings.py snippets, or template markup using Django template tags/variables -- can't run standalone via Judge0 or the browser preview, since it needs a real Django project. Only this course's pure-Python examples (example_lang == 'python', no Django imports) are actually runnable, so those still get the button below. #}

कई Fields के पार Validate करना

clean() को override करना आपको दो fields compare करने देता है, जैसे यह confirm करना कि एक password इसके confirmation field से match करता है।

उदाहरण: Validating Across Multiple Fields

Overriding clean() lets you compare two fields, like confirming a password matches its confirmation field.

markup
def clean(self):
    cleaned_data = super().clean()
    password = cleaned_data.get('password')
    confirm = cleaned_data.get('confirm_password')
    if password and confirm and password != confirm:
        raise ValidationError('Passwords do not match.')
    return cleaned_data
{# Django-only code -- models.py/views.py/urls.py/settings.py snippets, or template markup using Django template tags/variables -- can't run standalone via Judge0 or the browser preview, since it needs a real Django project. Only this course's pure-Python examples (example_lang == 'python', no Django imports) are actually runnable, so those still get the button below. #}

Custom Error Show करना

एक raised ValidationError अपने आप उस field के errors में attach हो जाता है और {{ form.as_p }} से display होता है।

उदाहरण: Showing the Custom Error

A raised ValidationError is automatically attached to that field's errors and displayed by {{ form.as_p }}.

markup
<form method="post">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Sign Up</button>
</form>
{# Django-only code -- models.py/views.py/urls.py/settings.py snippets, or template markup using Django template tags/variables -- can't run standalone via Judge0 or the browser preview, since it needs a real Django project. Only this course's pure-Python examples (example_lang == 'python', no Django imports) are actually runnable, so those still get the button below. #}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. एक clean method का नाम गलत रखना (जैसे clean_Email के बजाय clean_email) इसलिए Django इसे कभी call नहीं करता।
  2. एक clean_<field> method के आखिर में cleaned value return करना भूल जाना, जो silently उस field का data wipe कर देता है।
  3. एक plain Exception raise करना django.core.exceptions.ValidationError के बजाय, जिसे Django form के errors में attach नहीं कर सकता।
चैप्टर सारांश
  • एक clean_<fieldname> method एक specific field validate करता है और उसे cleaned value return करनी चाहिए।
  • clean() को override करना (कोई field name नहीं) एक साथ कई fields के बीच relationships validate करता है।
  • एक custom error message के साथ एक value reject करने के लिए django.core.exceptions.ValidationError raise करें।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.