首页 > 解决方案 > 使用 allauth get_login_redirect_url 登录后无法重定向到正确的 URL

问题描述

我有一个自定义用户模型,并且正在使用 django-allauth 来管理登录、注册、注销功能。我有 5 种用户类型,在每种类型登录后,它们将被定向到单独的页面。

通常LOGIN_REDIRECT_URL不适合我,因为无论哪种类型的用户登录,它都只能重定向到一个页面。我发现通过使用自定义帐户适配器和覆盖get_login_redirect_url()可以使它工作,所以我实现了它。

用户适配器.py

from django.conf import settings
from allauth.account.adapter import DefaultAccountAdapter
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import resolve_url, redirect

class MyAccountAdapter(DefaultAccountAdapter):

    def get_login_redirect_url(self, request):
        # path = super(MyAccountAdapter, self).get_login_redirect_url(request)
        current_user=request.user
        if current_user.user_type == 1:
            path='doc/dochome/'
        elif current_user.user_type == 2:
            path='lab/labhome/'
        elif current_user.user_type == 3:
            path='recep/recephome/'
        elif current_user.user_type == 4:
            path='patient/patienthome/'
        elif current_user.user_type == 5:
            path='admini/adminhome/'
        else:
            return HttpResponse("Your Rango account is disabled.")
        return path
        # .format(username=request.user.id)

设置.py

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_DIR = os.path.join(BASE_DIR, 'static')
TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')
MEDIA_DIR = os.path.join(BASE_DIR, 'media')
MEDIA_ROOT = MEDIA_DIR



# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'e$w4_d)z(z)4+5r98#@c4%52ymmd@96fv@x6#zzc7vs-aznqdo'

# 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',
    'django_extensions',
    'django.contrib.sites',
    #my app
    'health.apps.HealthConfig',
    #3rd party app
    'allauth', # for logging in
    'allauth.account', # for logging in
    'allauth.socialaccount',
]

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 = 'myhealth.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATE_DIR],
        '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',
                'django.template.context_processors.media'
            ],
        },
    },
]

WSGI_APPLICATION = 'myhealth.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


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',
    },
]
 # extensions for helping developing app
GRAPH_MODELS = {
  'all_applications': True,
  'group_models': True,
}


# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

AUTH_USER_MODEL = 'health.User'  #Substitute the default Django User model
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

AUTHENTICATION_BACKENDS = (
    # Needed to login by username in Django admin, regardless of `allauth`
    "django.contrib.auth.backends.ModelBackend",

    # `allauth` specific authentication methods, such as login by e-mail
    "allauth.account.auth_backends.AuthenticationBackend",
)

SITE_ID = 1

ACCOUNT_EMAIL_REQUIRED = True
# ACCOUNT_USER_MODEL_USERNAME_FIELD = None
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False
ACCOUNT_SESSION_REMEMBER = True
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_SIGNUP_FORM_CLASS = "health.forms.SignupForm"
ACCOUNT_ADAPTER = 'myhealth.users.adaptor.MyAccountAdapter'
# LOGIN_REDIRECT_URL = 'signup/'
ACCOUNT_LOGOUT_REDIRECT_URL = '/login/'
# ACCOUNT_EMAIL_VERIFICATION = 'mandatory'

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATICFILES_DIRS = [STATIC_DIR]
STATIC_URL = '/static/'

LOGIN_URL = '/login/'
MEDIA_URL = '/media/'

我的项目/urls.py

urlpatterns = [
    # path('accounts/', include('django.contrib.auth.urls')),
    # path('accounts/login/', views.user_login, name='login'),
    path('admin/', admin.site.urls),
    path('', include('health.urls')),
    path('', include('allauth.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

应用程序/urls.py

urlpatterns = [
    path('',views.user_login,name='login'),
    path('doc/dochome/',views.dochome,name='dochome'),
    path('recep/recephome/', views.recephome, name='recephome'),
    path('lab/labhome/', views.labhome, name='labhome'),
    path('admini/adminhome/', views.adminhome, name='adminhome'),
    path('patient/patienthome/', views.patienthome, name='patienthome'),
]

但是,在我成功登录后,它会被重定向到“login/doc/dochome/”,前面有多余的“login/”前缀。对于所有类型的用户来说都是一样的。我不知道出了什么问题,我在网上找不到任何其他类似的案例。有什么办法可以去掉'login/'前缀?

标签: pythondjangodjango-allauth

解决方案


我的头脑完全生锈了!棘手的解决方法是在我的所有路径前面添加 login/ :

urlpatterns = [
    path('',views.user_login,name='login'),
    path('login/doc/dochome/',views.dochome,name='dochome'),
    path('login/recep/recephome/', views.recephome, name='recephome'),
    path('login/lab/labhome/', views.labhome, name='labhome'),
    path('login/admini/adminhome/', views.adminhome, name='adminhome'),
    path('login/patient/patienthome/', views.patienthome, name='patienthome'),
]

推荐阅读