【问题标题】:Pass arguments using the HttpResponseRedirect in Django在 Django 中使用 HttpResponseRedirect 传递参数
【发布时间】:2014-05-31 17:03:19
【问题描述】:

我正在尝试将一些信息从views.py 传递到我的索引页(index.html)。一个通过了,我需要在索引页面中访问它。我试过用谷歌搜索它,但我不清楚。任何帮助,将不胜感激。我在下面附上了我尝试过的内容。

下面我要访问索引页中的值“bar”。我该怎么做?

def tempLogin(request):
   username = request.POST['username']
   password = request.POST['password']
   user = authenticate(username=username, password=password)
   if user is not None:
       if user.is_active:
           login(request, user)
           return HttpResponseRedirect(reverse('index',foo='bar'))
       else:
           return HttpResponseRedirect(reverse('index'))
   else:
       return HttpResponseRedirect(reverse('index'))

【问题讨论】:

    标签: django redirect backend http-redirect


    【解决方案1】:

    我经常看到这个问题,这表明对 Ht​​tpResponseRedirect 的作用缺乏了解。它所做的只是告诉浏览器去获取另一个 URL:所以你可以传递给它的唯一参数是那些其他 URL 模式所期望的参数。如果您的索引 URL 有一个可选空间供您放置名称值,那么您可以传递它。否则,您将需要以其他方式执行此操作:也许在会话中。

    【讨论】:

      【解决方案2】:

      您不能使用HttpResponseHttpResponseRedirect 执行此操作。您必须使用renderrender_to_response。有点像下面:

      from django.shortcuts import render
      
      def templogin(request):
          # Do all your processings here ...
          return render(request, 'index.html', {'bar': bar})
      

      传递给render 的第一个参数始终是request。第二个参数是模板的名称。在您的情况下,它是index.html。第三个参数是字典要添加到模板上下文的变量。在您的情况下,它是bar

      这里有更多关于renderDjango docs的信息。

      然后在您的模板中,您可以访问bar 变量,如下所示:

      <h1> {{ bar }} </h1>
      

      <span> Hello, {{ bar }}! </span>
      

      Django 会自动将{{ bar }} 替换为它的值。

      【讨论】:

        猜你喜欢
        • 2014-11-29
        • 1970-01-01
        • 1970-01-01
        • 2017-05-29
        • 1970-01-01
        • 2017-05-10
        • 2014-05-05
        • 2010-11-30
        • 2012-06-02
        相关资源
        最近更新 更多