【问题标题】:Calling a special (non-HTTP) URL from the form_valid method of a Django class-based view从基于 Django 类的视图的 form_valid 方法调用特殊(非 HTTP)URL
【发布时间】:2016-05-24 05:32:37
【问题描述】:

有一个 HTML 技巧,如果您执行 <a href="sms:14085551212?body=Hello my friend">New SMS Message</a>,点击 New SMS Message 会打开手机的原生 SMS 应用程序并使用提供的号码 (1-408) 预填充 To 字段-555-1212 在这种情况下),以及带有提供消息的body(在这种情况下是Hello my friend)。

有什么方法可以从基于 Django 类的视图的 form_valid 方法中调用相同的 href 字符串?准确地说,在这个form_valid 方法中,我收到了一个POST 变量,它是一个uuid。我需要在上面示例中编写的 href 字符串的 body 部分中使用 uuid

注意:我尝试了这个答案中遵循的方法:Django 1.4 - Redirect to Non-HTTP urls 它不能解决我的问题 - 我实际上没有重定向到任何地方,也没有收到错误。浏览器中的 URL 也不会改变。

我的代码是:

class UserPhoneNumberView(FormView):
    form_class = UserPhoneNumberForm
    template_name = "get_user_phonenumber.html"

    def form_valid(self, form):
        phonenumber = self.request.POST.get("mobile_number")
        unique = self.request.POST.get("unique")
        url = "http://example.com/"+unique
        response = HttpResponse("", status=302)
        body = "See this url: "+url
        nonhttp_url = "sms:"+phonenumber+"?body="+body
        response['Location'] = str(nonhttp_url)
        return response

【问题讨论】:

  • 我以为您可以使用 HttpResponseRedirect('sms:14085551212?body=Hello my friend') 但这不允许不安全的请求...不确定这是否有助于解决问题
  • 这可能是duplicate/solution,不过我还没有机会测试它
  • 试一试说。如果它有效,我会关闭它,因为它是重复的。否则,我会将我的发现添加到问题中并保持开放。感谢您的提示:-)
  • 302 状态通常是“没有任何改变”,这对我来说使用起来很奇怪。新请求是否显示在浏览器网络选项卡中? (在通常用 f12 显示的开发选项中)
  • 嗯,浏览器的网络标签没有任何反应(原来的 URL 一直在那里)。如果我尝试改用response['Location'] = 'http://google.com',则整个设置将完美执行(在浏览器的网络选项卡上显示多个相应的重定向)。

标签: python html django http django-views


【解决方案1】:

我认为你应该尝试@Selcuk 的建议:从 FormView 返回一个模板,其 HTML 代码类似于:

<html>
  <head>
    <meta http-equiv="refresh" content="0;URL={{ url }}" />
  </head>
  <body>
    <!-- The user will see this when they come back to the browser, 
         and if the SMS app does not open right away -->
    Waiting message 
  </body>
</html>

所以你的 django 视图会变成:

from urllib import quote
from django.shortcuts import render

class UserPhoneNumberView(FormView):
    form_class = UserPhoneNumberForm
    template_name = "get_user_phonenumber.html"

    def form_valid(self, form):
        phonenumber = self.request.POST.get("mobile_number")
        unique = self.request.POST.get("unique")
        url = "http://example.com/"+unique
        body = quote("See this url: "+url)
        nonhttp_url = "sms:"+phonenumber+"?body="+body
        context = {'url': nonhttp_url}
        return render(request, 'theTemplate.html', context)

我刚刚在我的手机上尝试过,我被重定向到我的短信应用程序。

【讨论】:

  • 但这不是立即重定向吗?我正在寻找仅在提交表单时发生的重定向(因为当它发生时我会处理一些相关代码)。这就是为什么我一直瞄准form_valid。我在这里发布了一个补充问题:stackoverflow.com/questions/35381763/…
  • 我的意思是从您的表单处理视图中返回此模板。
  • 我明白你的意思。一会我会回复你的。
猜你喜欢
  • 2015-09-04
  • 2012-12-28
  • 1970-01-01
  • 2018-08-21
  • 1970-01-01
  • 1970-01-01
  • 2013-05-12
  • 1970-01-01
  • 2012-01-25
相关资源
最近更新 更多