背景
在我的Django form_valid
的{{1}}方法中,我正在通过字符串连接构建一个网址。想象一下,所述URL为$.ajax
,其中view
是传递给此uuid
方法的POST变量。
在这种方法中,接下来我将构建一个自定义form_valid
对象,该对象将导致非http 网址为HttpResponse
。 nonhttp_url = "sms:"+phonenumber+"?body="+body
包含一些文字和我之前通过字符串连接形成的网址(例如'转到此网址:body
')。 [url]
是任何合法的手机号码。
这样构造的phonenumber
对象实际上是一个HTML技巧,用于打开手机的本机短信应用程序并预先填写电话号码和短信机构。它的常见用法是HttpResponse
。我本质上是在调用相同的东西,但是从我的Django视图的<a href="sms:phonenumber?body="+body">Send SMS</a>
方法内部。
问题:
如何确保我通过上面的str连接形成并传入非http网址的form_valid
部分的网址body
设置为Cache-Control
?实际上,我还想要no-cache
和no-store
。同样,我还需要must-revalidate
设置为Pragma
,no-cache
设置为Expires
,0
设置为Vary
。
当前代码:
*
答案 0 :(得分:0)
我认为你会像对待HTTP网址那样做吗?您可以按using the response as a dictionary设置标头,就像使用Location
标头一样。在这种情况下,添加如下行:response['Vary'] = '*'
。
为方便起见,您可以使用add_never_cache_headers()
添加Cache-Control
和Expires
标题。
以下是一个例子:
from django.utils.cache import add_never_cache_headers
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'] = nonhttp_url
# This will add the proper Cache-Control and Expires
add_never_cache_headers(response)
# Now just add the 'Vary' header
response['Vary'] = '*'
return response