简体   繁体   English

身份验证后,它不会重定向到django中的下一页

[英]After authentication it's not redirecting to next page in django

I am not able to redirect to next page in Django after authentication.I have already defined next in views.py file and calling that value but in URL its redirecting to Login page with URL as below: 身份验证后,我无法重定向到Django中的下一页。我已经在views.py文件中定义了next并调用了该值,但是在URL中使用以下URL将其重定向到Login页面:

And without @login_required its working properly 并且没有@login_required可以正常工作

After putting Username and Password redirecting to 将用户名和密码重定向后

http://127.0.0.1:8000/?next=/home/ http://127.0.0.1:8000/?next=/home/

But I want: 但我想要:

http://127.0.0.1:8000/home ( And display Home page) http://127.0.0.1:8000/home (并显示主页)

Please help. 请帮忙。

views.py views.py

from django.shortcuts import render
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib import auth
from django.conf import settings
from django.core.urlresolvers import reverse
def login(request):
    next = request.POST.get('next', 'home/')
    if request.method == "POST":
            username = request.POST['username']
            password = request.POST['password']
            user = authenticate(username=username, password=password)


            if user is not None:
                    if user.is_active:
                            auth.login(request, user)

                            return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL)
                    else:
                            return HttpResponse("Inactive user.")
            else:
                    return HttpResponseRedirect(settings.LOGIN_URL)
    return render(request, "login.html")

def logout(request):
    auth.logout(request)
    return HttpResponseRedirect(settings.LOGIN_URL)

@login_required(redirect_field_name='next')
def home(request):
    return render (request, "home.html")

App-urls.py: App-urls.py:

 from django.conf.urls import url

 from . import views

 urlpatterns = [
         url(r'^$', views.home, name='home'),
  ]

Project URL: 项目网址:

from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.auth import views


urlpatterns = [
         url(r'^admin/', admin.site.urls),
         url(r'^home/', include('login.urls', namespace="login")),
         url(r'^$', views.login),
         url(r'^logout/$', views.logout),
 ]

Settings.py: 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__)))


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '(i34g@645+vc8$@y9qd)_fo1l#k%78up_cheab#!(b24xv$!uj'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
      'login',
      'django.contrib.admin',
      'django.contrib.auth',
      'django.contrib.contenttypes',
      'django.contrib.sessions',
      'django.contrib.messages',
       'django.contrib.staticfiles',
  ]

 MIDDLEWARE_CLASSES = [
      'django.middleware.security.SecurityMiddleware',
      'django.contrib.sessions.middleware.SessionMiddleware',
      'django.middleware.common.CommonMiddleware',
      'django.middleware.csrf.CsrfViewMiddleware',
      'django.contrib.auth.middleware.AuthenticationMiddleware',
     'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
     'django.contrib.messages.middleware.MessageMiddleware',
     'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]

 ROOT_URLCONF = 'myproject.urls'

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

 WSGI_APPLICATION = 'myproject.wsgi.application'


 # Database
 # https://docs.djangoproject.com/en/1.9/ref/settings/#databases

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


 # Password validation
 # https://docs.djangoproject.com/en/1.9/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/1.9/topics/i18n/

 LANGUAGE_CODE = 'en-us'

 TIME_ZONE = 'UTC'

 USE_I18N = True

 USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/

STATIC_URL = '/static/'


LOGIN_URL = 'login/'
APPEND_SLASH = False

Login.html: 的login.html:

<!DOCTYPE html>
<center>

<section class="loginform cf">
<h1 style="color:blue"> User Login </h1>
<form name="login" method="post" accept-charset="utf-8" action="{% url   'login:home' %}">
{% csrf_token %}
<label for="usermail" align="center">User-Id </label>
<input type="alphanumeric" name="userid" >
<br \>
<label for="password" align="center">Password </label>
<input type="alphanumeric" name="password" >
<br \>
<input type="submit" value="Login" style="color:blue">
<input type="hidden" name="next" value="{{ next }}"/>
</center>
</form>
</section>

You've got some different things going on that are affecting it. 您正在发生一些影响它的事情。

Your urls.py file needs some cleaning up. 您的urls.py文件需要清理。 Because you've defined your own login/logout methods, you don't need to use the ones from django.contrib.auth.views . 因为您已经定义了自己的登录/注销方法,所以不需要使用django.contrib.auth.views So your base urls.py file should look like this: 因此,您的基本urls.py文件应如下所示:

from django.conf.urls import url
from django.contrib import admin
import login.views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^home/', include('login.urls')
    url(r'^$', login.views.login)
    url(r'^logout/$', login.views.logout)
]

Your login/urls.py file can stay the same. 您的login/urls.py文件可以保持不变。 Now we are pointing login/logout to your views not the django.contrib.auth.views . 现在,我们将登录/注销指向您的视图,而不是django.contrib.auth.views

You have settings.LOGIN_URL set to login/ but your urls.py file directs / to the login function. 您已经将settings.LOGIN_URL设置为login/但是您的urls.py文件将/定向到了登录功能。 For this answer, I'm changing settings.LOGIN_URL to / to match your url file. 对于此答案,我将settings.LOGIN_URL更改为/以匹配您的url文件。

Your login/views.py file only needed a few changes now that we've updated the urls.py file. 现在,我们已经更新了urls.py文件,您的login/views.py文件仅需要进行一些更改。

I cleaned up some of the import statements that were unnecessary and I removed redirect_field_name='next' from @login_required because 'next' is the default value. 我清理了一些不必要的导入语句,并从@login_required删除了redirect_field_name='next' ,因为'next'是默认值。

We need to check both the POST and GET objects to get the next parameter. 我们需要同时检查POSTGET对象以获得next参数。

The biggest change is after we authenticate the user and validate that they're active, instead of return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL) we just do return HttpResponseRedirect('/home') or send them to the next url that we grabbed from the POST / GET data. 最大的变化是在我们对用户进行身份验证并确认他们处于活动状态之后,而不是return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL)我们只是return HttpResponseRedirect('/home')或将其发送到我们从POST获取的next URL / GET数据。

from django.shortcuts import render
from django.contrib import auth
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseRedirect
from django.conf import settings

def login(request):
    next = request.POST.get('next', request.GET.get('next', ''))
    if request.method == "POST":
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = auth.authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                if next:
                    return HttpResponseRedirect(next)
                return HttpResponseRedirect('/home')
            else:
                return HttpResponse('Inactive user')
        else:
            return HttpResponseRedirect(settings.LOGIN_URL)
    return render(request, "login.html")

def logout(request):
    auth.logout(request)
    # Redirect back to login page
    return HttpResponseRedirect(settings.LOGIN_URL)


@login_required
def home(request):
    return render(request, "home.html")

Once you have that, unless there's something else I'm missing, @login_required should properly redirect to your login page if the user isn't logged in. 有了这些,除非我没有其他东西,否则如果用户未登录, @login_required应该正确重定向到您的登录页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM