使用allauth get_login_redirect_url

时间:2019-08-23 01:48:29

标签: python django django-allauth

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

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

users.adaptor.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)

settings.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/'

myproject / 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)

app / 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 /”前缀?

1 个答案:

答案 0 :(得分:0)

我的大脑完全生锈了!棘手的解决方法是在所有路径前添加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'),
]