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 manage.py startapp myapp
   

3. Define the necessary URLs in the myapp/urls.py 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/views.py 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
           else:
              messages.error(request, 'Invalid username or password.')
       return render(request, 'login.html')
   
   def logout_view(request):
       logout(request)
       return redirect('login')  # Replace 'login' with your login URL
   

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

  
  <h2>Login</h2>
   {% 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>
   </form>
   

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


   ...
   INSTALLED_APPS = [
       ...
       'myapp',
       ...
   ]
   
   ...


  AUTHENTICATION_BACKENDS = [
       'django.contrib.auth.backends.ModelBackend',
   ]
       

7. Apply migrations to create the necessary database tables:

   
   $ python manage.py makemigrations
   $ python manage.py migrate
   

8. Run the Django development server:


   $ python manage.py 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

Comments


bottom of page