Validate Unique Field in Form
A snippet showing how to validate unique fields in Django forms.
# forms.py
from django import forms
from django.contrib.auth.models import User
class UsernameForm(forms.Form):
username = forms.CharField(max_length=30)
def clean_username(self):
value = self.cleaned_data["username"]
if User.objects.filter(username__iexact=value).exists():
raise forms.ValidationError("This username is already taken.")
return value
Explanation:
-
Use case-insensitive lookups (e.g.,
iexact) to avoid duplicates differing by case.
- Category Forms & Validation
- Total Views 1264
- Last Modified 13 November, 2025
- Tags #forms #validation #unique #fields
Previous snippet
ModelForm Save with commit=False
Next snippet