我练习如何使用django登录,但在登录前无法重定向到页面 请教我如何做到非常感谢你
我的项目名称是:proj
我有一个应用名称:app1
当我转到http://127.0.0.1:8000/f/index/
时,它会重定向到http://127.0.0.1:8000/accounts/login/?next=/f/index/
在我输入用户名和密码后,
我想重定向到http://127.0.0.1:8000/f/index/
(通过参数?next=/f/index/
)但不知道该怎么做。
app1 / views.py:
from django.contrib.auth.decorators import login_required
@login_required
def index(request):
logger.info('test')
....
凸出/ urls.py:
urlpatterns = patterns('',
url(r'^accounts/login/$', 'proj.views.login'),
url(r'^accounts/logout/$', 'proj.views.logout'),
url(r'^accounts/auth/$', 'proj.views.auth_view'),
凸出/ views.py
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.contrib import auth
from django.core.context_processors import csrf
def login(request):
c={}
c.update(csrf(request))
return render_to_response('proj/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)
# return HttpResponseRedirect(request.POST.get('next')) #not work
else:
return HttpResponseRedirect('/accounts/invalid')
凸出/ login.html的:
{% if form.errors %}
<p class="error">Sorry.that's not valid </p>
{% endif %}
<form action="/accounts/auth/?next={{ request.get_full_path|urlencode }}" 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="submit" value="login" />
</form>
答案 0 :(得分:0)
在views.py
中尝试此操作:
if user is not None:
auth.login(request,user)
return HttpResponseRedirect('/f/index/')
答案 1 :(得分:0)
当您输入网址时,您之前未登录,并且django会重定向到网址:http://127.0.0.1:8000/accounts/login/?next=/f/index/
输入您的用户名和密码后,点击“提交”按钮,django会自动将您重定向到http://127.0.0.1:8000/f/index/
使用URLresolver。