[英]Django add custom header in the shorthand render method
To add in a CORS settings I can do something like this on a particular function:要添加 CORS 设置,我可以在特定的 function 上执行以下操作:
def clear(request):
# ... something
response = HttpResponse('OK')
response["Access-Control-Allow-Origin"] = "*"
return response
However, I'm having difficulty adding it on the shortform render
method:但是,我很难将它添加到简短的render
方法中:
def function(request):
# how to modify the response header here?
return render(request, 'page.html', data)
How would I update some of the headers in the render response?我将如何更新渲染响应中的一些标头?
render()
method combines a given template
with a given context dictionary
and returns an HttpResponse
object with that rendered text. render()
方法将给定的template
与给定的context dictionary
相结合,并返回带有渲染文本的HttpResponse
object。 Refer here .参考这里。
You can store the result of the render function in a variable called as response and then set cookies to it as you would normally do.您可以将渲染 function 的结果存储在名为 response 的变量中,然后像往常一样将 cookies 设置为它。
Your view function should be您的观点 function 应该是
def function(request):
response = render(request, 'page.html', data)
response["Access-Control-Allow-Origin"] = "*"
return response
render
also returns an HttpResponse
object: render
还返回一个HttpResponse
object:
Combines a given template with a given context dictionary and returns an
HttpResponse
object with that rendered text.将给定的模板与给定的上下文字典相结合,并返回带有呈现文本的HttpResponse
object。
So you can do the exact same thing you did above on the 'raw' HttpResponse
object:因此,您可以在“原始” HttpResponse
object 上执行与上述完全相同的操作:
def function(request):
response = render(request, 'page.html', data)
response["Access-Control-Allow-Origin"] = "*"
return response
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.