Django

Create a User Registration Page using Django Built-in User Model

πŸ“Œ 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
  • email
  • 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 User model
  • 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 identity
  • email β†’ user email
  • password and confirm_password β†’ password confirmation
  • PasswordInput hides typed password
  • clean() 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:

βœ… Output:

User registered successfully!

❌ If username already exists:

Username already exists.

❌ If passwords do not match:

Passwords do not match.

🧠 How It Works

  1. User opens registration page
  2. Enters username, email, password, confirm password
  3. Form is submitted using POST
  4. Django validates the form
  5. clean() checks password match
  6. View checks username uniqueness
  7. create_user() saves the user
  8. 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

  1. Add first name and last name fields
  2. Add custom success redirect after registration
  3. Show login link after successful registration
  4. Validate minimum password length
  5. 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

Django Practice Exercise

Examples of Array Functions in PHP

Basic Programs in PHP

Registration Form Using PDO in PHP

Inserting Information from Multiple CheckBox Selection in a Database Table in PHP

programmingempire

princites.com

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *