DEV Community

Sharon Yelenik
Sharon Yelenik

Posted on

How to Set Up Signup, Login, and Logout using Django's Middleware

  1. Create a Python project containing an app with files apps.py, models.py, views.py, and forms.py, and create a virtual environment:
django-admin startproject <project_name>  
cd <project_name>  
python3 -m venv <virtual_environment_name>   
pip install django    
source <virtual_environment_name>/bin/activate   
python manage.py startapp <app_name>
Enter fullscreen mode Exit fullscreen mode
  1. In your `settings.py` file, make sure:
    • `django.contrib.auth.middleware.AuthenticationMiddleware` is included under the MIDDLEWARE setting.
    • django.contrib.auth and django.contrib.contenttypes are listed under INSTALLED_APPS in settings.py. Add your app to INSTALLED_APPS, as well. Then, run manage.py migrate to create the necessary database tables.
  1. In the views.py file, create a signup view and a landing_page view, and use the @login_required decorator for all your views that require login:
# django_app/views.py

from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import UserCreationForm

def signup(request):
   if request.method == 'POST':
       form = UserCreationForm(request.POST)
       if form.is_valid():
           form.save()
           return redirect('login')
   else:
       form = UserCreationForm()
   return render(request, 'signup.html', {'form': form})
def landing_page(request):
   if request.user.is_authenticated:
       return render(request, 'my_template.html')
   return render(request, 'landing_page.html')

@login_required
def my_app(request):
    # Action logic here
   return render(request, 'my_template.html')
Enter fullscreen mode Exit fullscreen mode
  1. Create a signup.html template, a registration/login.html template, a landing_page.html template, and a my_template.html template:
<!-- signup.html -->

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Sign Up</title>
</head>
<body>
   <h2>Sign Up</h2>
   <form method="post">
       {% csrf_token %}
       {{ form.as_p }}
       <button type="submit">Sign Up</button>
   </form>
</body>

<!-- registration/login.html -->
<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Login</title>
</head>
<body>
   <h2>Login</h2>
   <form method="post">
       {% csrf_token %}
       {{ form.as_p }}
       <button type="submit">Login</button>
   </form>
</body>
</html>

<!-- landing_page.html -->
<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Welcome to Your Site</title>
</head>
<body>
   <h1>Welcome to Your Site</h1>
   <p>Sign up or log in to access the features:</p>
   <a href="{% url 'signup' %}">Sign Up</a>
   <a href="{% url 'login' %}">Log In</a>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode
  1. Import from django.contrib.auth import views as auth_views in your url.py file and add the new paths:
# urls.py

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

urlpatterns = [
   path('admin/', admin.site.urls),
   path('accounts/login/', auth_views.LoginView.as_view(), name='login'),
   path('accounts/logout/', auth_views.LogoutView.as_view(), name='logout'),
   path('', views.landing_page, name='landing_page'),
   path('signup/', views.signup, name='signup'),
   path('my_app/', views.my_app, name='my_app'),
  # Your app’s paths
]
Enter fullscreen mode Exit fullscreen mode
  1. To allow logging in, singing in, and logging out, add this script to the rest of the templates in your app:
{% if user.is_authenticated %}
   <p>Welcome, {{ user.username }}!</p>
   <a href="{% url 'logout' %}">Logout</a>
{% else %}
   <a href="{% url 'signup' %}">Sign up</a>
   <a href="{% url 'login' %}">Login</a>
{% endif %}
Enter fullscreen mode Exit fullscreen mode
  1. In settings.py, add the following code to open the respective templates whenever a user logs in and out:
LOGIN_REDIRECT_URL = 'my_app'  # Redirect to upload page after login
LOGOUT_REDIRECT_URL = 'login'   # Redirect to login page after logout
Enter fullscreen mode Exit fullscreen mode

For more information about Python built-in and third-party security features, see Python Security Essentials for Your Apps.

Top comments (0)