从视图调用模板标签 - CSRF不被填充 [英] Calling a templatetag from a view -- CSRF not gtting populated

查看:85
本文介绍了从视图调用模板标签 - CSRF不被填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



templatetags / tags.py

$ b $我正在使用include_tags来生成我网站中许多不同地方重复的部分网页。 b

  @ register.inclusion_tag('chunk_template.html')
def output_chunk(object,edit):
...#很多在这里设置工作,我不想在视图中复制
return {...}

在页面上的AJAX提交表单时,我需要刷新由output_chunk()输出的完全相同的HTML。为了避免在视图中完全重写output_chunk(),请我按照此解答中的建议进行了以下操作在视图中使用模板标签



views.py

  def chunk(request,...):
context = Context({...,'request':request})
template_string =
{%load output_chunk from标签%}
{%output_chunk ...%}

t =模板(template_string)
返回HttpResponse(t.render(上下文))

这是一切正常,除了chunk_template.html调用 {%csrf%} ,当我以标准的方式调用模板标签时,它可以工作,但是当我以这种有趣的方式调用时(不要两次编写相同的代码),而不是这样。



(对于更简单的模板标签,当我从内部调用返回render(request,template_name,context)时,这可以正常工作那么,是否有更好的方法从视图内调用模板标签,以便正确调用所有的中间件?或者有什么我可以添加到这个黑客,使其正常工作?

解决方案

需要使上下文为RequestContext。 / p>

  context = RequestContext(request,{....})


I am using inclusion_tags to generate portions of my pages that repeat in many different places across my site.

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 { ... }

Upon AJAX submit of a form on the page, I need to refresh the very same HTML outputted by output_chunk(). To avoid completely rewriting output_chunk() in a view, 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))

This is all working fine, except chunk_template.html calls {% csrf %}, which works when I call the template tag the standard way, but not when I call in this somewhat hacky way (to avoid writing the same code twice).

(For simpler template tags, this works fine when I call return render (request, template_name, context) from within the view.)

So, is there a better way to call the template tag from within the view to get all the middleware invoked properly? Or is there something I can add to this hack to make it work properly?

解决方案

Need to make the context a RequestContext.

context = RequestContext(request, {....})

这篇关于从视图调用模板标签 - CSRF不被填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆