π Introduction
Django provides a built-in User model for authentication.
Using this model, we can create features like:
- user registration
- login
- logout
- password management
In this program, we will create a registration page where a new user can sign up using:
- username
- password
- confirm password
This is a very important topic for real-world applications.
π― Program Statement
π Create a user registration page using Django built-in User model.
π§ Concept
This program uses:
- Django built-in
Usermodel - Django
forms.py create_user()method- POST form submission
βοΈ Step 1: Import User Model and Create Registration Form
π File: forms.py
πΉ Path:
myproject/myapp/forms.py
πΉ Code:
from django import forms
class RegisterForm(forms.Form):
username = forms.CharField(label='Enter Username', max_length=100)
email = forms.EmailField(label='Enter Email')
password = forms.CharField(label='Enter Password', widget=forms.PasswordInput)
confirm_password = forms.CharField(label='Confirm Password', widget=forms.PasswordInput)
def clean(self):
cleaned_data = super().clean()
password = cleaned_data.get('password')
confirm_password = cleaned_data.get('confirm_password')
if password and confirm_password and password != confirm_password:
raise forms.ValidationError("Passwords do not match.")
return cleaned_data
π§ Explanation
usernameβ for login identityemailβ user emailpasswordandconfirm_passwordβ password confirmationPasswordInputhides typed passwordclean()checks whether both passwords match
βοΈ Step 2: Create Registration View
π File: views.py
πΉ Path:
myproject/myapp/views.py
πΉ Code:
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from .forms import RegisterForm
def register_user(request):
success = False
error_message = None
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
email = form.cleaned_data['email']
password = form.cleaned_data['password']
if User.objects.filter(username=username).exists():
error_message = "Username already exists."
else:
User.objects.create_user(
username=username,
email=email,
password=password
)
success = True
form = RegisterForm()
else:
form = RegisterForm()
return render(request, 'register_user.html', {
'form': form,
'success': success,
'error_message': error_message
})
π§ Explanation
User.objects.create_user()creates a new user safely- Password is stored in encrypted form
- Username uniqueness is checked before creating account
- On success, the form is cleared
βοΈ Step 3: URL Mapping
π File: urls.py
πΉ Path:
myproject/myproject/urls.py
πΉ Code:
from django.contrib import admin
from django.urls import path
from myapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('register/', views.register_user, name='register_user'),
]
βοΈ Step 4: Create Template
π File: register_user.html
πΉ Path:
myproject/templates/register_user.html
πΉ Code:
<!DOCTYPE html>
<html>
<head>
<title>User Registration</title>
</head>
<body>
<h1>User Registration Page</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Register</button>
</form>
<hr>
{% if success %}
<h2 style="color: green;">User registered successfully!</h2>
{% endif %}
{% if error_message %}
<h2 style="color: red;">{{ error_message }}</h2>
{% endif %}
</body>
</html>
π§ Explanation
{{ form.as_p }}renders all fields- success and error messages are displayed conditionally
- CSRF token is required because form uses POST
βοΈ Step 5: Make Sure Auth App is Enabled
π File: settings.py
πΉ Path:
myproject/myproject/settings.py
πΉ Confirm these apps exist:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
]
π§ Explanation
Djangoβs built-in User model belongs to:
'django.contrib.auth'
So this app must be enabled.
βοΈ Step 6: Apply Migrations for Auth Tables
If not already done, run:
python manage.py migrate
π§ Explanation
This creates the authentication-related tables, including the built-in auth_user table.
βοΈ Step 7: Run Server
python manage.py runserver
π Step 8: Output
Open:
π http://127.0.0.1:8000/register/
β Example Input:
- Username: kavita
- Email: kavita@example.com
- Password: 12345678
- Confirm Password: 12345678
β Output:
User registered successfully!
β If username already exists:
Username already exists.
β If passwords do not match:
Passwords do not match.
π§ How It Works
- User opens registration page
- Enters username, email, password, confirm password
- Form is submitted using POST
- Django validates the form
clean()checks password match- View checks username uniqueness
create_user()saves the user- Success message is shown
π₯ Key Concepts
Built-in User Model
from django.contrib.auth.models import User
Used for authentication-related user data.
Create User
User.objects.create_user(...)
Creates user with hashed password.
Password Match Validation
def clean(self):
Used for custom cross-field validation.
Password Input Widget
widget=forms.PasswordInput
Hides typed password characters.
β οΈ Common Errors
β Using create() instead of create_user()
Do not use:
User.objects.create(...)
because password will not be hashed properly.
Use:
User.objects.create_user(...)
β Forgot django.contrib.auth in INSTALLED_APPS
Then Django authentication system will not work properly.
β Password mismatch not checked
Always validate password and confirm_password.
β Duplicate username
Username must be unique for each user.
β Forgot to run migrations
The built-in user table must exist in database.
π§ͺ Practice Questions
- Add first name and last name fields
- Add custom success redirect after registration
- Show login link after successful registration
- Validate minimum password length
- Check duplicate email also
π€ Viva Questions & Answers
1. What is the built-in User model in Django?
The built-in User model is provided by Django for authentication and user management. It stores data like username, email, password, and permissions.
2. Why do we use create_user() instead of create()?
create_user() stores the password in hashed form, which is secure. create() would store it as plain text unless handled manually.
3. What is the purpose of PasswordInput widget?
It hides the entered password characters in the browser for security.
4. Why do we use clean() method in the registration form?
clean() is used to perform custom validation involving multiple fields, such as checking whether password and confirm password match.
5. Why is username uniqueness important?
Each user must have a unique username so that Django can identify users correctly during login.
6. What is the use of django.contrib.auth?
It provides Djangoβs built-in authentication system, including the User model, login, logout, and permission handling.
7. Why do we run migrations before registration?
Migrations create the necessary authentication tables in the database, including the user table.
8. What happens if passwords do not match?
The form becomes invalid, and a validation error message is shown to the user.
9. Can we also store email in the built-in User model?
Yes, the built-in User model includes an email field.
10. Why is this program important?
It is the foundation of user authentication systems and is used in most real Django applications.
π Navigation
π Next Post: Implement Login, Logout, and Protected Page using Authentication
π Back to List: Django Programs (60 Questions with Solutions)
Further Reading
Introduction to Django Framework and its Features
Examples of Array Functions in PHP
Registration Form Using PDO in PHP
Inserting Information from Multiple CheckBox Selection in a Database Table in PHP
- Angular
- ASP.NET
- C
- C#
- C++
- CSS
- Dot Net Framework
- HTML
- IoT
- Java
- JavaScript
- Kotlin
- PHP
- Power Bi
- Python
- Scratch 3.0
- TypeScript
- VB.NET
