我正在使用inclus_tags生成部分网页,这些部分会在我网站的许多不同位置重复出现。
templatetags / tags.py
@register.inclusion_tag('chunk_template.html')
def output_chunk(object, edit):
... # Lots of set up work here that I don't want to duplicate in the view
return { ... }
当AJAX在页面上提交表单时,我需要刷新output_chunk()输出的相同HTML。为避免在视图中完全重写output_chunk(),I did the following as recommended in this answer about how to use templatetags in views:
views.py
def chunk(request, ...):
context = Context({..., 'request': request })
template_string = """
{% load output_chunk from tags %}
{% output_chunk ... %}
"""
t = Template(template_string)
return HttpResponse(t.render(context))
这一切都运行正常,除了chunk_template.html调用{% csrf %}
,当我以标准方式调用模板标记时,它工作,但是当我以这种有点hacky方式调用时(以避免两次编写相同的代码) )。
(对于更简单的模板标签,当我从视图中调用return render (request, template_name, context)
时,这种方法很有效。)
那么,是否有更好的方法从视图中调用模板标记以正确调用所有中间件?或者有什么我可以添加到这个黑客,以使其正常工作?
答案 0 :(得分:1)
我不明白问题的核心,但你总是可以手动拉取令牌(中间件调用此函数)。
from django.middleware.csrf import get_token
csrf = get_token(request)
答案 1 :(得分:0)
需要将上下文设为RequestContext。
context = RequestContext(request, {....})