• OUR GLOBAL PRESENCE:
  • USA
  • IN
  • SG
  • PT

Django provides a robust user authentication system through its django.contrib.auth library. This guide will help you set up login functionality step by step.


Step 1: Setting Up Your Django Project

i. Create a Project and App

Run the following commands to create a new project and app:

django-admin startproject myproject
cd myproject
python manage.py startapp accounts

ii. Add the App to Installed Apps

In settings.py, add your app to the INSTALLED_APPS list:

INSTALLED_APPS = [
...,
'accounts',
'django.contrib.auth',
'django.contrib.contenttypes',
...,
]

iii. Apply Migrations

Run the following command to apply the necessary database migrations:

python manage.py migrate

Step 2: Configuring URLs for Authentication

Django provides pre-built views for login and logout.

i. Create a urls.py File in the accounts App

Create a urls.py file inside the accounts app and add the following code:

from django.urls import path
from django.contrib.auth import views as auth_views

urlpatterns = [
path('login/', auth_views.LoginView.as_view(template_name='accounts/login.html'), name='login'),
path('logout/', auth_views.LogoutView.as_view(), name='logout'),
]

ii. Include the App’s URLs in the Project URLs

In your project’s urls.py, include the accounts app’s URLs:

from django.urls import path, include

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

Step 3: Creating the Login Template

Django’s LoginView requires an HTML template to render the login form.

i. Create a Template Directory

Inside the accounts app, create the directory structure: templates/accounts/.

ii. Add a Login Template

Create a file named login.html in templates/accounts/ with the following content:

<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Login</button>
</form>
</body>
</html>

Step 4: Customizing Login Behavior

By default, Django redirects users to /accounts/profile/ after login. To change this:

i. Update the settings.py File

Add the following lines:

LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/accounts/login/'

This will redirect users to the homepage after login and to the login page after logout.


Step 5: Protecting Views with Authentication

To restrict access to certain views, use the @login_required decorator.

i. Create a Protected View in views.py

Add the following code:

pythonCopy codefrom django.contrib.auth.decorators import login_required
from django.shortcuts import render

@login_required
def dashboard(request):
    return render(request, 'accounts/dashboard.html')

ii. Add a URL for the Protected View

In urls.py, add the following line:

pythonCopy codepath('dashboard/', dashboard, name='dashboard'),

iii. Create a Dashboard Template

Create a dashboard.html file in templates/accounts/ with the following content:

<!DOCTYPE html>
<html>
<head>
<title>Dashboard</title>
</head>
<body>
<h1>Welcome, {{ user.username }}!</h1>
<a href="{% url 'logout' %}">Logout</a>
</body>
</html>

Step 6: Styling the Login Page (Optional)

To enhance the look of your login page, use a CSS framework like Bootstrap.

Replace the login.html content with the following:

<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
</head>
<body class="container mt-5">
<div class="row justify-content-center">
<div class="col-md-6">
<h2 class="text-center">Login</h2>
<form method="post" class="mt-4">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-primary w-100">Login</button>
</form>
</div>
</div>
</body>
</html>

Final Words

With these steps, you’ve implemented a secure login system using Django’s contrib.auth library. This setup leverages Django’s powerful built-in tools to simplify authentication while maintaining security.

You can further extend this functionality by adding user registration, password reset, or third-party authentication using packages like django-allauth.

Happy Coding! 🎉

We will zealously try to help you by providing technical support. We are open to inquiries or requests.

+1-2252762741

+916280560026

1945 Brightside Drive, Baton Rouge, LA -70820

Contact Us

Get in touch!

We are available for a friendly chat to discuss your business needs, no obligation.

Drop a message here, and we will get back to you soon.