【问题标题】:Django HttpResponseRedirect is using the actual contents of index.html in urlDjango HttpResponseRedirect 在 url 中使用 index.html 的实际内容
【发布时间】:2015-07-14 19:22:28
【问题描述】:

来自 php 背景的 django 新手,通过民意调查应用程序演练,现在我想创建一个登录页面,但我遇到了各种错误。这是我感到困惑的事情。我有一个 ACCOUNTS [app],在那个目录中我有一个 TEMPLATES [子文件夹],其中只有一个文件夹,也称为 ACCOUNTS。里面是我所有的模板,包括 index.html。

├───migrations
│   └───__pycache__
├───templates
│   └───accounts
|         ->the index.html file
└───__pycache__

<html>
<head>
    <title>INDEX</title>
</head>
<body>
INDEX
</body>
</html>

当我运行 url localhost:8000/accounts/ 时,它实际上会获取 index.html 的内容并将其插入到 URL 中

http://127.0.0.1:8000/accounts/%3Chtml%3E%0A%3Chead%3E%0A%09%3Ctitle%3EINDEX%3C/title%3E%0A%3C/head%3E%0A%3Cbody%3E%0AINDEX%0A%3C/body%3E%0A%3C/html%3E

帐户 -views.py

from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response, redirect, render
from django.template import RequestContext, loader
from . import LoginView
from django.contrib.auth.decorators import login_required
from django.contrib import auth
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse

@login_required(login_url='/login/')
def index(request):
    template = loader.get_template('accounts/index.html')
    context = RequestContext(request, {
        'Kitty': 5
    })
    return HttpResponseRedirect(template.render(context))

谁能解释一下(1)为什么我当前的代码会这样(2)可能的修复?

谢谢,我愿意阅读或学习一些必要的东西。

【问题讨论】:

    标签: php django


    【解决方案1】:

    如果您想将用户重定向到另一个 URL,HttpResponseRedirect 类很有用。

    def index(request):
        return HttpResponseRedirect("/other-url/")
    

    在你的例子中,你已经渲染了一个模板上下文。因为您将呈现的模板传递给HttpResponseRedirect,所以它将其视为要重定向到的 url。

    最简单的解决方法是改用常规的HttpResponse

    from django.http import HttpResponse
    
    @login_required(login_url='/login/')
    def index(request):
        template = loader.get_template('accounts/index.html')
        context = RequestContext(request, {
            'Kitty': 5
        })
        return HttpResponse(template.render(context))
    

    渲染模板并返回响应非常常见,因此您可以改用render 快捷方式来缩短代码。

    from django.shortcuts import render
    
    @login_required(login_url='/login/')
    def index(request):
        template_name = 'accounts/index.html'
        context = {
            'Kitty': 5
        }
        return render(request, template_name, context)
    

    【讨论】:

    • 感谢您用我能理解的术语进行非常清晰的解释!
    • 我在提交表单后尝试完成同样的事情。我需要在传递context 时使用HttpResponseRedirect。我的视图返回模板的整个 HTML。有什么想法吗?
    • @joshlsullivan 您在传递上下文时无法重定向。见this answer。如果这没有帮助,请打开一个新问题。
    • @Alasdair 非常好。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2014-05-08
    • 1970-01-01
    • 1970-01-01
    • 2011-08-14
    • 2014-05-31
    • 1970-01-01
    • 2014-08-19
    • 2011-11-26
    相关资源
    最近更新 更多