问题
There's this HTML trick where if you do <a href="sms:14085551212?body=Hello my friend">New SMS Message</a>
, clicking New SMS Message opens up the phone's native SMS app and pre-fills the To
field with the number provided (1-408-555-1212 in this case), and the body
with the message provided (Hello my friend
in this case).
Is there any way I can call this same href
string from the form_valid
method of a Django class-based view? To be exact, in this form_valid
method I'm receiving a POST
variable that is a uuid
. I need to use that uuid
in the body
section of the href string I've written in the example above.
Note: I tried the approach followed in this answer: Django 1.4 - Redirect to Non-HTTP urls It doesn't solve my problem - I actually don't redirect anywhere, nor do I get an error. The URL in the browser doesn't change either.
My code is:
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
回答1:
I think you should try @Selcuk's suggestion: returning a template from the FormView with HTML code similar to:
<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>
So your django view would become:
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)
I just tried on my phone, and I got redirected to my SMS app.
来源:https://stackoverflow.com/questions/35373245/calling-a-special-non-http-url-from-the-form-valid-method-of-a-django-class-ba