几个小时以来,我一直在试图弄清楚但没有结果。{{ next }}
变量对我不起作用(我的意思是它是空的),但是以这种方式工作{{ request.REQUEST.next|urlencode }}
。但是,不会使用 GET 或 POST 将我重定向到下一个位置。Django 可以自动执行此操作,还是我必须在每个视图中手动编写代码?
我正在使用 DJango 1.3。
这是我的一段代码:
设置.py
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'django.core.context_processors.static',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.core.context_processors.request',
)
LOGIN_URL = '/'
登录表单
{% load url from future %}
<form action="{% url 'user:login' %}" method="post">
{{ form.username }}<br />
{{ form.password }}<br />
<input type="hidden" name="next" value="{{ request.REQUEST.next|urlencode }}" />
{% csrf_token %}
<button id="submit" class="btn btn-primary" type="submit">Login</button>
</form>
登录视图
from django.shortcuts import render, redirect
from django.contrib import auth
from .forms import LoginForm
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
user = auth.authenticate(
username=form.cleaned_data["username"],
password=form.cleaned_data["password"]
)
auth.login(request, user)
#I added this piece of code in order to achieve the redirection
#but i preffer a lot if Django could do it for me.
next = request.POST.get('next', None)
if next:
return redirect(next)
else:
errors = form.errors.items()
return render(request, 'base/homepage.html', {'form':form, 'errors':errors} )
return redirect('base:homepage')
谢谢!