0

我知道这个问题已经以另一种方式得到了回答,但我仍然不知道如何在用户登录后重定向。我知道 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 的新手,并且对这个概念并不完全清楚。感谢帮助!!

4

1 回答 1

0

login(request, user)您需要返回一些 http 响应之后,例如它是从 ome 模板呈现的页面。但是如果你想去其他页面,你可以返回HttpResponseRedirect('/needed_url'),你会得到一个指向 url 的请求。

您也可以request.POST['referrer'])根据需要指向上一页的 url。

Django 文档 - HttpResponseRedirect

PS 另外我可以说点什么<form action="/some/url/" ...地址你会去管理你的表格数据。如果使用 Django,您的urls.py文件中应该有一条记录,例如(r'^some/url/$', some_function),它将使用指定的函数处理您的请求。

于 2013-01-20T11:23:21.623 回答