【问题标题】:redirecting from one place to another从一个地方重定向到另一个地方
【发布时间】:2013-01-18 22:03:06
【问题描述】:

我在 html 文件中有一个按钮定义为 ;

<input type="submit" value="Log In" name="login_button" style="width: 109px; "/>

此按钮位于 sample.com 上。用户来并单击此按钮,然后当前网页http://127.0.0.1:8000/sample 更改为在 login.html 中定义的http://127.0.0.1:8000/sample2。出于这个原因,我已经做到了;

def auth(request):
  if 'login_button' in request.POST:
    // redirect the web page to the sample2.com
  return render_to_response('login.html', {} )

我试过redirect("http://127.0.0.1:8000/sample2),但没有成功。我怎样才能转到另一个页面。

在这个函数上定义的其他网页

  def message(request):
          current_date_T = Template ("<p style=\"text-align: right;\">\
                                {{Date|truncatewords:\"8\"}}\
                            </p>")

          # --
          return HttpResponse(html)

网址文件

  urlpatterns = patterns('',
            ('^sample2/$', message),
            ('^sample/$', auth),
  )

首先打开的页面是示例,其中有一个按钮。单击示例上的按钮后将调用 Sample2。

【问题讨论】:

  • 你试过return声明吗? return redirect("sample2.com)
  • @AamirAdnan 你能看看我编辑的问题吗?
  • @AamirAdnan 最后一次编辑,我修正了我的错误,你能帮帮我吗?
  • 将您的urls.py 文件内容也发布到您定义了sample2 url的地方
  • @AamirAdnan 看看编辑。

标签: python html django web


【解决方案1】:

您只需要redirect 而不是render_to_response。请尝试以下操作:

def auth(request):
    if 'login_button' in request.POST:
        # redirect the web page to the /sample2
        return redirect('/sample2/')
    else:
        # Do something else

【讨论】:

    【解决方案2】:

    首先为您的网址定义名称:

    urlpatterns = patterns('',
        url('^sample2/$', message, name="message_view"),
        url('^sample/$', authentication, name="auth_view"),
    )
    

    然后使用 url 反向解析技术,使用 url 的名称获取视图的 url:

    def auth(request):
        if request.method == 'POST':
            // redirect the web page to the sample2.com
            return redirect(reverse('message_view'))
        return render_to_response('login.html', {} )
    

    我不知道这里重定向的目的是什么。但这就是它的工作原理。

    【讨论】:

    • 在您的代码中,哪个部分正在检查按钮是否被按下?
    • 如果按钮被按下,那么请求方法是POST而不是GET。所以如果request.method == 'POST' 那么这意味着按钮被按下了。
    • 如果页面上有一个二三的按钮,如何检测出点击的是哪一个?
    • 那你为什么要使用表格?在模板中为每个 url 使用简单的 href 标记:&lt;a href="{% url message_view %}"&gt;Go to Message View&lt;/a&gt;
    • 顺便说一句,你的解决方案也给出了同样的错误CSRF cookie not set.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多