繁体   English   中英

登录后Django Python重定向

[英]Django Python redirect after login

我知道已经回答了这个问题,这是另一种方法,但是我仍然无法弄清楚用户登录后如何重定向。我知道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说它找不到URL。总而言之,我不得不说我是Web编程+ django的新手。 + python并没有完全清楚这个概念,谢谢您的帮助!

login(request, user)您需要返回一些http响应,例如,这是从ome模板呈现的页面。 但是,如果您想转到其他页面,则可以返回HttpResponseRedirect('/needed_url')并且您将获得指向指向url的请求。

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

Django文档-HttpResponseRedirect

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM