我知道这个问题已经以另一种方式得到了回答,但我仍然不知道如何在用户登录后重定向。我知道 Django 带有内置网站,但我需要一个自定义登录表单,看起来像这样(这是 HTML):
{% if user.is_authenticated %}
<!-- Authenticate account menu -->
{% else %}
<h3>Login</h3>
<form action="/app/login/" method="post" accept-charset="utf-8">
<label for="username">Username</label>
<input type="text" name="username" value="" id="username" />
<label for="password">Password</label>
<input type="password" name="password" value="" id="password" />
<p><input type="submit" value="Login →"></p>
</form>
{% endif %}
我的 views.py 看起来像这样:
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import Context, loader
from django.contrib.auth import authenticate, login
from django.views.generic.simple import *
def index(request):
if request.method == 'POST':
user = authenticate(username=request.POST['username'], password=request.POST['password'])
if user is not None:
if user.is_active:
login(request, user)
# success
if request.POST['next']:
return HttpResponseRedirect(request.POST['next'])
else:
return HttpResponseRedirect('/')
else:
# disabled account
return direct_to_template(request, 'inactive_account.html')
else:
# invalid login
return render_to_response("app/index.html")
return render_to_response("app/index.html")
我并没有完全自己编写代码。我发现重定向发生在 html 文件中的某个位置:<form action="/app/login/
. 但是 django 说它找不到网址。总而言之,我不得不说我是网络编程+django+python 的新手,并且对这个概念并不完全清楚。感谢帮助!!