Django не может перенаправить на index или admin после входа в систему

Невозможно перенаправить на страницу панели администратора или в индекс после входа в систему, даже если имя пользователя и пароль верны

для 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")

для settings.py

после запуска сервера с помощью "python manage.py runserver 0.0.0.0:8000"

введите описание изображения здесь вечно торчит здесь http://192.168.0.81:8000/admin/login/?next=/admin/

Проблема, похоже, связана с этой настройкой

SESSION_COOKIE_SECURE = True

Эта настройка отправляет сессионные cookie только по протоколу https. поскольку вы запускаете сайт по протоколу http, это вызывает проблемы.

Просто обновите настройку на false. (не рекомендуется использовать на производстве)

SESSION_COOKIE_SECURE = False

Подробнее об этом читайте здесь SESSON_COOKIE_SECURE

Вернуться на верх