You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django技术问题:应用与Admin登录互斥,需实现双独立会话

Fixing Independent Sessions for Main App and Admin Panel

Hey there! Let's tackle that frustrating issue where logging into your main myapp.com kicks you out of the /admin panel (and vice versa). The root problem is Django's default session setup uses a single cookie for the entire domain—so one login overwrites the other's session. Here's how to fix this properly, building on your existing session middleware work:

Core Idea

We'll dynamically use different session cookie names depending on whether the request is for the admin panel or the main app. This way, the browser stores two separate cookies, keeping sessions completely isolated.

Step 1: Custom Session Middleware

Replace your current middleware with this updated version that switches cookie names based on the request path:

import time
from importlib import import_module
from django.conf import settings
from django.contrib.sessions.backends.base import UpdateError
from django.core.exceptions import SuspiciousOperation
from django.contrib.sessions.middleware import SessionMiddleware
from django.utils.http import cookie_date
from django.utils.cache import patch_vary_headers

class PathBasedSessionMiddleware(SessionMiddleware):
    def process_request(self, request):
        # Switch cookie name based on request path
        if request.path.startswith('/admin/'):
            session_cookie_name = 'admin_sessionid'
        else:
            session_cookie_name = 'sessionid'
        
        # Initialize session with the correct cookie
        engine = import_module(settings.SESSION_ENGINE)
        session_key = request.COOKIES.get(session_cookie_name)
        request.session = engine.SessionStore(session_key)
        # Attach the cookie name to the session for later use in response
        request.session.cookie_name = session_cookie_name

    def process_response(self, request, response):
        try:
            accessed = request.session.accessed
            modified = request.session.modified
            empty = request.session.is_empty()
            cookie_name = getattr(request.session, 'cookie_name', settings.SESSION_COOKIE_NAME)
        except AttributeError:
            return response
        else:
            if accessed:
                patch_vary_headers(response, ('Cookie',))
            if modified or settings.SESSION_SAVE_EVERY_REQUEST:
                if request.session.get_expire_at_browser_close():
                    max_age = None
                    expires = None
                else:
                    max_age = request.session.get_expiry_age()
                    expires_time = time.time() + max_age
                    expires = cookie_date(expires_time)
                try:
                    request.session.save()
                except UpdateError:
                    raise SuspiciousOperation(
                        "The request's session was deleted before the request completed. "
                        "The user may have logged out in a concurrent request."
                    )
                # Set cookie with the correct name
                response.set_cookie(
                    cookie_name,
                    request.session.session_key,
                    max_age=max_age,
                    expires=expires,
                    domain=settings.SESSION_COOKIE_DOMAIN,
                    path=settings.SESSION_COOKIE_PATH,
                    secure=settings.SESSION_COOKIE_SECURE or None,
                    httponly=settings.SESSION_COOKIE_HTTPONLY or None,
                    samesite=settings.SESSION_COOKIE_SAMESITE,
                )
            if empty:
                response.delete_cookie(
                    cookie_name,
                    domain=settings.SESSION_COOKIE_DOMAIN,
                    path=settings.SESSION_COOKIE_PATH,
                )
        return response

Step 2: Update Settings.py

Swap out Django's default session middleware with your custom one in settings.py:

MIDDLEWARE = [
    # ... other middleware ...
    # Replace the default SessionMiddleware with your custom one
    'myapp.middleware.PathBasedSessionMiddleware',  # Update the path to your middleware file
    # ... other middleware ...
]

Step 3: Test and Cleanup

  • Clear your browser's existing cookies for myapp.com to avoid conflicts with old session data.
  • Open two tabs: one for myapp.com and one for myapp.com/admin. Log into both—you should stay logged into both without being kicked out.

Key Notes

  • Session Isolation: The two sessions are completely separate because they use different cookies. Logging out of one won't affect the other.
  • Session Engine Compatibility: This works with any Django session engine (database, cache, file, etc.) since we're just changing the cookie name, not how sessions are stored.
  • No Extra Views Needed: You don't have to modify Django's admin login or your main app's login views—they'll automatically use the correct cookie based on the path.

That should solve your problem! You can now use both the main app and admin panel in separate tabs without constant re-logins.

内容的提问来源于stack exchange,提问作者Ruben

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:49:46