Can't redirect to the admin dashboard page or to the index after logging in even though the username and password are correct
for views.py
from django.shortcuts import redirect
from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User
from django.contrib import messages
from auth.views import AuthView
class LoginView(AuthView):
def get(self, request):
if request.user.is_authenticated:
# If the user is already logged in, redirect them to the home page or another appropriate page.
return redirect("index") # Replace 'index' with the actual URL name for the home page
# Render the login page for users who are not logged in.
return super().get(request)
def post(self, request):
if request.method == "POST":
username = request.POST.get("email-username")
password = request.POST.get("password")
if not (username and password):
messages.error(request, "Please enter your username and password.")
return redirect("login")
if "@" in username:
user_email = User.objects.filter(email=username).first()
if user_email is None:
messages.error(request, "Please enter a valid email.")
return redirect("login")
username = user_email.username
user_email = User.objects.filter(username=username).first()
if user_email is None:
messages.error(request, "Please enter a valid username.")
return redirect("login")
authenticated_user = authenticate(request, username=username, password=password)
if authenticated_user is not None:
# Login the user if authentication is successful
login(request, authenticated_user)
# Redirect to the page the user was trying to access before logging in
if "next" in request.POST:
return redirect(request.POST["next"])
else: # Redirect to the home page or another appropriate page
return redirect("index")
else:
messages.error(request, "Please enter a valid username.")
return redirect("login")
for settings.py
"""
Django settings for web_project project.
Generated by 'django-admin startproject' using Django 4.2.1.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""
import os
from pathlib import Path
from django.utils.translation import gettext_lazy as _
from dotenv import load_dotenv
from .template import TEMPLATE_CONFIG, THEME_LAYOUT_DIR, THEME_VARIABLES
load_dotenv() # take environment variables from .env.
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get("SECRET_KEY", default='')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.environ.get("DEBUG", 'True').lower() in ['true', 'yes', '1']
# https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts
ALLOWED_HOSTS = ["192.168.0.81","localhost", "0.0.0.0", "127.0.0.1"]
# Current DJANGO_ENVIRONMENT
ENVIRONMENT = os.environ.get("DJANGO_ENVIRONMENT", default="local")
# Application definition
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"apps.dashboards",
"auth.apps.AuthConfig"
]
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"whitenoise.middleware.WhiteNoiseMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.locale.LocaleMiddleware",
"web_project.language_middleware.DefaultLanguageMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
ROOT_URLCONF = "config.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [BASE_DIR / "templates"],
"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",
"config.context_processors.language_code",
"config.context_processors.my_setting",
"config.context_processors.get_cookie",
"config.context_processors.environment",
],
"libraries": {
"theme": "web_project.template_tags.theme",
},
"builtins": [
"django.templatetags.static",
"web_project.template_tags.theme",
],
},
},
]
WSGI_APPLICATION = "config.wsgi.application"
# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
}
# Password validation
# https://docs.djangoproject.com/en/4.2/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",
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/
# Enable i18n and set the list of supported languages
LANGUAGES = [
("en", _("English")),
("fr", _("French")),
("ar", _("Arabic")),
("de", _("German")),
# Add more languages as needed
]
# Set default language
# ! Make sure you have cleared the browser cache after changing the default language
LANGUAGE_CODE = "en"
TIME_ZONE = "UTC"
USE_I18N = True
USE_L10N = False
USE_TZ = True
LOCALE_PATHS = [
BASE_DIR / "locale",
]
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/
STATIC_URL = "/static/"
STATIC_ROOT = BASE_DIR / "staticfiles"
STATICFILES_DIRS = [
BASE_DIR / "src" / "assets",
]
# Default URL on which Django application runs for specific environment
BASE_URL = os.environ.get("BASE_URL", default="http://192.168.0.81:8000")
# if not DEBUG:
# STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
# Template Settings
# ------------------------------------------------------------------------------
THEME_LAYOUT_DIR = THEME_LAYOUT_DIR
TEMPLATE_CONFIG = TEMPLATE_CONFIG
THEME_VARIABLES = THEME_VARIABLES
# Email Settings
# ------------------------------------------------------------------------------
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "smtp.gmail.com"
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = ""
EMAIL_HOST_PASSWORD = ""
# Loginyour mail
# ------------------------------------------------------------------------------
LOGIN_URL = "/login/"
LOGOUT_REDIRECT_URL = "/login/"
# Session
# ------------------------------------------------------------------------------
SESSION_ENGINE = "django.contrib.sessions.backends.db"
SESSION_COOKIE_SECURE = True
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SAMESITE = None
SESSION_COOKIE_AGE = 3600
CSRF_TRUSTED_ORIGINS = [
"http://192.168.0.81:8000",
"http://0.0.0.0:8000",
"http://localhost:5050",
]
after runserver with "python manage.py runserver 0.0.0.0:8000"
enter image description here always stuck in here http://192.168.0.81:8000/admin/login/?next=/admin/
The issue seems to be with this setting
SESSION_COOKIE_SECURE = True
This setting send session cookie only over https. as you are running site over http, cause issue.
Just update the setting to false.(not suggesting on production)
SESSION_COOKIE_SECURE = False
Read more about it here SESSON_COOKIE_SECURE