Django login and register Tutorial

nitish96
Nitish Sharma
Published on: December 24, 2024
Updated on: December 25, 2024
Django login and register Tutorial blog

In this tutorial, we will be creating a user authentication system using Django that includes user registration and login functionality. Django's built-in authentication system makes it easy to implement these features while following best practices.

Prerequisites

Before we get started, ensure you have the following

•    Python installed on your system
•    Django installed (use pip install django)
•    A basic understanding of Django’s MVC architecture

Setting Up the Project

1.    Create a New Django Project

django-admin startproject auth_project
cd auth_project

2.    Create a New Django App

Python manage.py startapp accounts

3.    Register the App Add ‘accounts’ to the INSTALLED_APPS list your settings.py file.

INSTALLED_APPS = [
    ...,
    'accounts',
]

Creating the User Model

We’ll use Django’s default user model. If you need a custom user model, Refer to Django’s Custom user model documentation

Building the Registration View

1.    Create a Registration From

In accounts/forms.py

from django import forms
from django.contrib.auth.models import User

class UserRegistrationForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput, label='Password')
    confirm_password = forms.CharField(widget=forms.PasswordInput, label='Confirm Password')

    class Meta:
        model = User
        fields = ['username', 'email', 'password']

    def clean(self):
        cleaned_data = super().clean()
        password = cleaned_data.get('password')
        confirm_password = cleaned_data.get('confirm_password')

        if password != confirm_password:
          raise forms.ValidationError("Passwords do not match")

2.    Create the Registration View

In accounts/views.py

from django.shortcuts import render, redirect
from .forms import UserRegistrationForm

def register(request):
    if request.method == 'POST':
        form = UserRegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('login')
    else:
        form = UserRegistrationForm()
    return render(request, 'accounts/register.html', {'form': form})

3.    Creating the Registration Template

In accounts/templates/accounts/register.html

<h2>Register</h2>
<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Register</button>
</form>

Building the Login View

1.    Create the Login View

Use Django’s built-in LoginView.
In accounts/views.py

from django.contrib.auth.views import LoginView
class UserLoginView(LoginView):
    template_name = 'accounts/login.html'

2.    Create the Login Template

In accounts/templates/accounts/login.html

<h2>Login</h2>
<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Register</button>
</form>

Configuring URLs

In accounts/urls.py

from django.urls import path
from .views import register, UserLoginView

urlpatterns = [
    path('register/', register, name='register'),
    path('login/', UserLoginView.as_view(), name='login'),
]

In auth_project/urls.py

from django.contrib import admin
from django.urls import path, include
urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/', include('accounts.urls')),
]

Run Application 

python manage.py runserver

Visit http://127.0.0.1:8000/accounts/register/ to register a new user and

http://127.0.0.1:8000/accounts/login/ to log in.

Conclusion

Congratulations! You have successfully implemented a basic login and registration system in Django. From here, you can extend the functionality by adding password reset, email verification, and user profile.
If you have any questions or concerns, please feel free to let us know. Our team will connect with you shortly to assist.

Comments

Login to leave a comment.

Build Software Application with Impact Hive