top of page

How you can Create a login System using Django

Sure! Here's an example of how you can create a login system using Django:

1. Set up a Django project:

   $ django-admin startproject myproject
   $ cd myproject

2. Create a Django app:

   $ python startapp myapp

3. Define the necessary URLs in the myapp/ file:

   from django.urls import path
   from . import views
   urlpatterns = [
       path('login/', views.login_view, name='login'),
       path('logout/', views.logout_view, name='logout'),

4. Create the necessary views in the myapp/ file:

   from django.shortcuts import render, redirect
   from django.contrib.auth import authenticate, login, logout
   from django.contrib import messages
   def login_view(request):
       if request.method == 'POST':
           username = request.POST.get('username')
           password = request.POST.get('password')
           user = authenticate(request, username=username, password=password)
           if user is not None:
              login(request, user)
               return redirect('home')  # Replace 'home' with your desired homepage URL
              messages.error(request, 'Invalid username or password.')
       return render(request, 'login.html')
   def logout_view(request):
       return redirect('login')  # Replace 'login' with your login URL

5. Create a login template in myapp/templates/login.html:

   {% if messages %}
       {% for message in messages %}
           <p>{{ message }}</p>
       {% endfor %}
   {% endif %}
   <form method="post" action="{% url 'login' %}">
       {% 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>

6. Update the myproject/ file to include your app and the required authentication settings:



7. Apply migrations to create the necessary database tables:

   $ python makemigrations
   $ python migrate

8. Run the Django development server:

   $ python runserver

Now, when you navigate to http://localhost:8000/login/, you should see the login form. Users can enter their credentials, and upon successful login, they will be redirected to the homepage. To log out, users can visit http://localhost:8000/logout/.

Please note that this is a basic example to get you started with a login system. You may need to customize it further based on your specific requirements.

Related Posts

See All

Django CRUD (Create, Retrieve, Update, Delete)

Step 1: Create the Django project and app Open your terminal (or command prompt) and run the following commands: # Create the Django project django-admin startproject crud_project cd crud_project # C


bottom of page