Django после @login требуется перенаправление на следующий

я чувствую, что это простой вопрос, и я просто пропустил 1 маленький шаг.

я хочу сделать любое количество следующего (как термин в следующем параметре):

[not signed in] -> profile -> login?next=/accounts/profile/ -> auth -> profile.
[not signed in] -> newsfeed -> login?next=/newsfeed/` -> auth -> newsfeed.

а я сейчас пойду:

[not signed in] -> profile -> login?next=/accounts/profile/ -> auth -> loggedin
[not signed in] -> newsfeed -> login?next=/newsfeed/ -> auth -> loggedin

я ищу, чтобы как-то передать next параметр из формы на login to auth и auth редирект на этот параметр

в настоящее время я пытаюсь в моем login.html:

<input type='text' name="next" value="{{ next }}">

однако это не получает следующего значения. Я вижу из панели инструментов отладки:

GET data
Variable    Value
u'next'     [u'/accounts/profile/']

views:

def auth_view(request):
  username = request.POST.get('username', '')
  password = request.POST.get('password', '')
  user = auth.authenticate(username=username, password=password)

  if user is not None:
    auth.login(request, user)
    print request.POST
    return HttpResponseRedirect(request.POST.get('next'),'/accounts/loggedin')
  else:
    return HttpResponseRedirect('/accounts/invalid')

login.html:

{% extends "base.html" %}

{% block content %}

  {% if form.errors %}
  <p class="error"> Sorry, you have entered an incorrect username or password</p>
  {% endif %}
  <form action="/accounts/auth/" method="post">{% csrf_token %}
    <label for="username">User name:</label>
    <input type="text" name="username" value="" id="username">

    <label for="password">Password:</label>
    <input type="password" name="password" value="" id="password">

    <input type='text' name="next" value="{{ request.GET.next }}">
    <input type="submit" value="login">
  </form>

{% endblock %}

settings:

from django.conf.urls import patterns, include, url

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:

    url(r'^admin/', include(admin.site.urls)),
    ('^accounts/', include('userprofile.urls')),

    url(r'^accounts/login/$', 'django_yunite.views.login'),
    url(r'^accounts/auth/$', 'django_yunite.views.auth_view'),
    url(r'^accounts/logout/$', 'django_yunite.views.logout'),
    url(r'^accounts/loggedin/$', 'django_yunite.views.loggedin'),
    url(r'^accounts/invalid/$', 'django_yunite.views.invalid_login'),

)

settings:

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

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

TEMPLATE_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',
    'debug_toolbar',
    'userprofile',
)

MIDDLEWARE_CLASSES = (
    '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 = 'django_yunite.urls'

WSGI_APPLICATION = 'django_yunite.wsgi.application'

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

LANGUAGE_CODE = 'en-ca'

TIME_ZONE = 'EST'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    ('assets', '/home/user/GitHub/venv_yunite/django_yunite/static/'),
    )

TEMPLATE_DIRS = (
    './templates',
    '/article/templates',
)

STATIC_ROOT = "/home/user/Documents/static/"

AUTH_PROFILE_MODULE = 'userprofile.UserProfile'

состояние печати показывает пустое u'next'

4 ответов


строка запроса неявно передается в любое представление без необходимости написания специального кода.

все, что вам нужно сделать, это убедиться, что next ключ передается из фактической формы входа в систему (в вашем случае это форма, которая отображается в /accounts/login/), к /accounts/auth вид.

для этого вам нужно убедиться, что у вас есть обработчик контекста шаблона запроса (django.core.context_processors.request) включено в настройках. Для этого сначала необходимо импортировать значение по умолчанию для TEMPLATE_CONTEXT_PROCESSORS, затем добавьте обработчик запросов к нему в settings.py, например:

from django.conf import global_settings

TEMPLATE_CONTEXT_PROCESSORS = global_settings.TEMPLATE_CONTEXT_PROCESSORS + (
    "django.core.context_processors.request",
) 

затем в виде:

<form method="POST" action="/accounts/auth">
    {% csrf_token %}
    <input type="hidden" name="next" value="{{ request.GET.next }}" />
    {{ login_form }}
    <input type="submit">
</form>

теперь в вашей /accounts/auth вид:

def foo(request):
    if request.method == 'POST':
        # .. authenticate your user


        # redirect to the value of next if it is entered, otherwise
        # to /accounts/profile/
        return redirect(request.POST.get('next','/accounts/profile/'))

то, что вы ищете-это логин декоратор.

в вашем views.py

from django.contrib.auth.decorators import login_required

@login_required(login_url="/accounts/login/")
def profile( request ):
   """your view code here"""
   return HttpResponse("boo ya", "text/html")

тогда в вашем urls.py добавить url аутентификации

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

и наконец: убедитесь, что у вас есть django.ВНО.auth в установленных приложениях и AuthenticationMiddleware установлен.

settings.py

INSTALLED_APPS = (
   -- snip --,
   'django.contrib.auth',
   )


MIDDLEWARE_CLASSES = (
   -- snip --,
   'django.contrib.auth.middleware.AuthenticationMiddleware',
   )

ваш шаблоны/регистрация/вход.HTML-код

<form method="POST" action="/accounts/login/">
   {% csrf_token %}
   <input type="hidden" name="next" value="{{ next }}" />
   {{ login_form }}
   <input type="submit">
</form>

столкнулся с подобной ситуацией некоторое время назад. Чтобы решить эту проблему, я написал своего собственного декоратора -

def validate_request_for_login(f):
    def wrap(request):
        if not request.user.is_authenticated():
            return redirect("/login?next=" + request.path)
        return f(request)
    return wrap

выше декоратор проверяет аутентификацию пользователя. Если пользователь не аутентифицирован, перенаправьте пользователя на страницу входа, передав url из объекта запроса.


то, что я закончил, это следующее. Мне это кажется немного халтурной работой. Есть ли лучший способ использовать login с csrf?

views:

def login(request):
  c={}
  c.update(csrf(request))
  if 'next' in request.GET:
    c['next'] = request.GET.get('next')
  return render_to_response('login.html', c)

def auth_view(request):
  username = request.POST.get('username', '')
  password = request.POST.get('password', '')
  user = auth.authenticate(username=username, password=password)

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

    if request.POST.get('next') != '':
      return HttpResponseRedirect(request.POST.get('next'))
    else:
      return HttpResponseRedirect('/accounts/loggedin')
  else:
    return HttpResponseRedirect('/accounts/invalid')

login.html:

<input type="hidden" name="next" value="{{ next }}"/>