Above is my django project structure and i have two django apps.
I am using mongodb as my database and not using user authentication module.
I am using session variable to store username when user is logged. but i am getting error while using session variable.
raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: WSGI application 'CMS.wsgi.application' could not be loaded; Error importing module.
wsgi.py ---> main project file
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'CMS.settings')
application = get_wsgi_application()
authentication/views.py
def login(request):
error_message = None
if request.method == 'POST':
username_value = request.POST.get('username')
password_value = request.POST.get('password')
try:
user = SignUp.objects.get(username=username_value)
# Check if the provided password matches the hashed password in the database
if check_password(password_value, user.password):
# Successful login
response = HttpResponse("Login successful!")
request.session['username'] = user.username
return redirect('home')
else:
error_message = "Invalid username or password"
except DoesNotExist:
error_message = "User does not exist"
return render(request, 'authentication/login.html', {'error_message': error_message})
settings.py
from pathlib import Path
from mongoengine import connect
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure--#u^llr^ji5f70u-vm-99-59(m4010v_$a%bga2-puf2-d%l*3'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'mongoengine',
'Student_management_app',
'core',
'authentication',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'CMS.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'CMS.wsgi.application'
connect('CMS', host='localhost', port=27017)
MONGODB_DATABASES = {
'default': {
'ENGINE': 'django_mongoengine.mongoengine',
'NAME': 'CMS',
'HOST': 'CMS',
'PORT': 27017,
}
}
# Configure MongoDB for sessions
SESSION_ENGINE = 'django.contrib.sessions.backends.mongo'
SESSION_SAVE_EVERY_REQUEST = True
# MongoDB configuration for sessions
SESSION_ENGINE = 'django_mongoengine.sessions'
SESSION_MONGO_DB = 'CMS' # Use the same MongoDB database name as your main database
SESSION_MONGO_COLLECTION = 'django_sessions'
# Password validation
# https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
STATIC_URL = 'static/'
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
STATICFILES_DIRS = [
BASE_DIR / "static",
]
core/views.py
from django.http import HttpResponse
from django.shortcuts import render
from mongoengine import DoesNotExist
from authentication.models import SignUp
def home(request):
default_content = {
'title': 'Welcome to College Management System',
}
# Retrieve the username from cookies
username = request.session.get('username')
if username:
try:
user = SignUp.objects.get(username=username)
# Your existing code that uses user_id goes here
# For example, you can fetch additional user data using user_id
# Update default_content or perform other actions based on user information
except DoesNotExist:
# Handle the case where the user does not exist
return HttpResponse("User does not exist")
return render(request, 'core/base.html', {'content': default_content, 'username': username})
base.html
<!-- base.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ content.title }}</title>
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'core/base.css' %}">
</head>
<body>
<div>
<nav>
<ul>
<li><a href="{% url 'home' %}">Home</a></li>
<li class="register"><a href="{% url 'signup' %}">Signup</a></li>
<li class="register"><a href="{% url 'login' %}">Login</a></li>
</ul>
</nav>
</div>
<div>
{% if username %}
<h2>Welcome, {{ username }}!</h2>
<a href="{% url 'user_logout' %}">Logout</a>
{% else %}
<p>You are not logged in.</p>
{% endif %}
</div>
{% block content %}
{% if error_message %}
<p class="alert alert-danger">{{ error_message }}</p>
{% endif %}
{% endblock %}
</body>
</html>