Hi Dev,
In this tutorial, you'll learn how to implement Django form password validation with a working example. This Django password validation example ensures strong password policies while collecting user credentials in forms. This tutorial covers creating a project, defining validators, rendering the form, and handling validation logic.
Django’s built-in password validation helps improve security and user safety. The validators ensure that passwords are not too common, not fully numeric, and are not too similar to user details.
- Similarity: Ensures passwords are not similar to username, first name, last name, or email.
- Minimum length: Default minimum is 8, but customizable (e.g. 6).
- Common Password: Blocks use of common passwords (Django includes 20,000+).
- Numeric: Passwords cannot be purely numeric.
Let’s get started with this step-by-step Django password validation tutorial.
Step 1: Create a Project
In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:
django-admin startproject exampleapp
Step 2: Create an App
Now we'll create a single app called core to handle our forms. Use the command below:
python3 manage.py startapp core
Step 3: Update setting.py
Add the core app to the INSTALLED_APPS list and configure password validators as shown:
INSTALLED_APPS = [
...
'core',
]
AUTH_PASSWORD_VALIDATORS = [
{'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'},
{'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 'OPTIONS': {'min_length': 6}},
{'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'},
{'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'},
]
Step 4: Create a Form
Create a forms.py file and define the custom form with password confirmation:
from django import forms
from django.contrib.auth import password_validation
class EmpRegistration(forms.Form):
username = forms.CharField(label='Username',
widget=forms.TextInput(attrs={'class': 'form-control'}))
password = forms.CharField(label='Password',
widget=forms.PasswordInput(attrs={'class': 'form-control'}),
help_text=password_validation.password_validators_help_text_html)
confirm_Password = forms.CharField(label='Confirm Password',
widget=forms.PasswordInput(attrs={'class': 'form-control'}))
def clean(self):
cleaned_data = super().clean()
password1 = self.cleaned_data.get('password')
cpassword = self.cleaned_data.get('confirm_Password')
if password1 != cpassword:
raise forms.ValidationError('Confirm Password is not same as Password')
password_validation.validate_password(password1)
return self.cleaned_data
Step 5: Creating the Views
Define the view to handle form rendering and POST data:
from django.shortcuts import render
from .forms import EmpRegistration
def detail_form(request):
if request.method == "POST":
form = EmpRegistration(request.POST)
if form.is_valid():
print('Username:', form.cleaned_data['username'])
print('Password:', form.cleaned_data['password'])
print('Confirm Password:', form.cleaned_data['confirm_Password'])
else:
form = EmpRegistration()
return render(request, 'home.html', {'form': form})
Step 6: Creating the Templates
Create the template core/templates/home.html with the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tuts-Station.com</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
<style type="text/css">
body{
background-color: #f7fcff;
}
</style>
</head>
<body>
<div class="container mt-5 pt-5">
<div class="row d-flex justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">
<h4>Django Form Password Validation Example - <span class="text-primary">Tuts-Station.com</span></h4>
</div>
<div class="card-body">
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-success">Submit</button>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Step 7: Creating Urls
Update core/urls.py and project’s main urls.py:
# core/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('password', views.detail_form, name='detail_form'),
]
# exampleapp/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('core.urls')),
]
Run the Server
Start your Django development server:
python manage.py runserver
Then visit:
http://localhost:8000/password
I hope this example helps you implement secure and user-friendly password validation in Django forms!
Frequently Asked Questions (FAQs)
1. How does Django validate passwords?
Django uses a set of built-in validators like minimum length, common passwords, similarity to personal info, and numeric checks to enforce password policies.
2. How can I change the minimum password length in Django?
You can update the MinimumLengthValidator option in AUTH_PASSWORD_VALIDATORS in settings.py.
3. Can I use custom password validators?
Yes, Django allows writing custom password validators by creating a class that implements validate() and get_help_text() methods.
4. What if I want to display error messages directly on the form?
Use {{ form.errors }} in your template to display validation errors near the form fields.
5. Is it mandatory to use Django’s password validation?
No, but it's strongly recommended for better security and user protection.