Invoking templatetag from view - CSRF without uppercase

I use include_tags to create parts of my pages that repeat in many different places on 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 { ... } 

After AJAX submits the form on the page, I need to update the same HTML as output_chunk (). To avoid overwriting output_chunk () in the view completely, I did the following, as recommended in this answer, on how to use templatetags in the 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)) 

Everything works fine except chunk_template.html calls {% csrf %} , which works when I call the template tag in the standard way, but not when I call it in a 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 the view.)

So, is there a better way to call a template tag from a view in order to properly run all middleware? Or is there something I can add to this hack so that it works correctly?

0
source share
2 answers

You need to make a RequestContext context.

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

I do not understand the essence of the problem, but you can always manually extract the token (middleware calls this function).

 from django.middleware.csrf import get_token csrf = get_token(request) 
+1
source

All Articles