819 views
asked in Python by
Coding example of Login register logout in python django

1 Answer

answered by

In a Django web application, the implementation of user authentication, including features like login, register, and logout, is a common requirement. Django offers built-in features and modules that make handling user authentication straightforward. Here's a basic guide on implementing login, register, and logout functionality in a Django application:

1. Setting up Django Project

Assuming you have already created a Django project, ensure that you have the necessary apps installed:

pip install django

2. Creating a Django App

Create a new Django app for handling authentication:

django-admin startproject chirags_project

cd chirags_project

python manage.py startapp accounts

And now open your project in text editor like vscode, sublime etc.

3. Configuring Django Settings

Add the newly created app and required authentication settings in your project's settings.py:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'LoginRegisterLogout',
        'USER': 'postgres',
        'PASSWORD': 'admin@123',
        'HOST': 'localhost',
    }
}

# settings.py

INSTALLED_APPS = [
    ...
    'accounts',
]

# Authentication settings add in the last

LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/'

4. Implementing User register

In your accounts/views.py:

# accounts/views.py
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login

def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            return redirect('home')  # Redirect to your home page
    else:
        form = UserCreationForm()
    return render(request, 'users/register.html', {'form': form})

5. Creating Template base.html

Create a base template (accounts/templates/users/base.html) in your accounts app:

<!-- accounts/templates/users/base.html -->
{% block content %}
{% endblock content %}

6. Creating register Template

Create a register template (accounts/templates/users/register.html) in your accounts app:

<!-- accounts/templates/users/register.html -->
{% extends 'users/base.html' %}
{% block content %}
    <a href="{% url 'login' %}">Login</a> | <a href="{% url 'register' %}">Register</a>
    <h2>Register</h2>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Register</button>
    </form>
{% endblock %}

7. home.html

<!-- accounts/templates/users/home.html -->
{% extends 'users/base.html' %}
{% block content %}
    {% if request.user.is_authenticated %}
        <p>{{ request.user.username }}</p>
        <a href="{% url 'logout' %}">Logout</a>
    {% else %}
        <a href="{% url 'login' %}">Login</a>
        <a href="{% url 'register' %}">Register</a>
    {% endif %}
    <h1>Welcome!</h1>
{% endblock %}

8. Implementing Login and Logout Views

Add the following views to your accounts/views.py:

# accounts/views.py
from django.contrib.auth import authenticate, login, logout
def user_login(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            return redirect('home')  # Redirect to your home page
    return render(request, 'users/login.html')
def user_logout(request):
    logout(request)
    return redirect('home')  # Redirect to your home page

def user_home(request):
    return render(request, 'users/home.html')

9. Creating Login Template

Create a login template (templates/users/login.html) in your accounts app:

<!-- accounts/templates/users/login.html -->
{% extends 'users/base.html' %}
{% block content %}
    <a href="{% url 'login' %}">Login</a> | <a href="{% url 'register' %}">Register</a>
    <h2>Login</h2>
    <form method="post">
        {% csrf_token %}
        <label for="username">Username:</label>
        <input type="text" name="username" required><br>
        <label for="password">Password:</label>
        <input type="password" name="password" required><br>
        <button type="submit">Login</button>
        <a href="{% url 'register' %}">Don't have Click here to create.</a>
    </form>
{% endblock %}

10. URL Configuration

Create and Configure URLs in your accounts/urls.py:

# accounts/urls.py

from django.urls import path
from .views import register, user_login, user_logout, user_home
urlpatterns = [
    path('', user_home, name='home'),
    path('register/', register, name='register'),
    path('login/', user_login, name='login'),
    path('logout/', user_logout, name='logout'),
]

Include these URLs in your project's urls.py:

# project/urls.py

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

11. Open pgAdmin (I am using PostgreSQL database) and create database i. e LoginRegisterLogout1

12. Run Migrations

Run migrations to apply changes to the database:

python manage.py makemigrations
python manage.py migrate

10. Run the Development Server

Start the development server:

python manage.py runserver

Visit 

http://127.0.0.1:8000/accounts/register/
http://127.0.0.1:8000/accounts/login/
and
http://127.0.0.1:8000/accounts/logout/

to test your register, login, and logout functionality.

This is a basic example, and you may wish to customize it according to your project's requirements. This may involve adding features such as user profiles, password reset functionality, and more.

Most popular tags

laravel postgresql laravel-10 replication ha postgresql mongodb laravel-11 mongodb database mongodb tutorial ubuntu 24.04 lts streaming-replication mysql database laravel postgresql backup laravel login register logout database mysql php laravel 11 - login with otp valid for 10 minutes. user and admin registration user and admin login multiauth technlogy asp.net asp.net c# mysql master slave replication centos linux laravel sql server schedule backup autobackup postgresql django python haproxy load balancer install self sign ssl laravel 11 gaurds zabbix 7 how to install graylog on ubuntu 24.04 lts | step-by-step asp.net core mvc .net mvc network upload c# ssl integration sql server on ubuntu 22.04 lts mssql server ms sql server sql server user access in postgres mysql password change cent os linux configure replica laravel 11 socialite login with google account google login kubernetes (k8s) install nginx load balancer install install and configure .net 8.0 in ubuntu 24.04 lts php in iis php with iis php tutorial chirags php tutorials chirags php tutorial chirags tutorial laravel 11 guards mongodb sharding metabase business analytics metabase postgresql 16 to postgresql 17 postgresql migration letsencrypt mongodb crud rocky linux laravel custom captcha laravel 11 captcha laravel captcha mongo dll php.ini debian 12 nginx apache nextcloud gitea in ubuntu git gitea npm error node js mysql ndb cluster mysql cluster ssl oracle login register logout in python debian windows shell batch file bat file time stamp date time shopping cart in laravel centos rhel swap memeory rhel 5.5
...