Django Template Templates in Views

Hey. I need to update my own template tag --right_side.py - through Ajax. Is there a way to import a template tag in a view and return it as HttpResponse, because I don’t want to give up my custom template tag (it works fine on other pages) and doesn’t encode a new view action that really looks like it,

Having a link to call using Ajax or loading it as inside

if request.isAjax ():

Both are good for me.

+7
source share
3 answers

This is very useful for me when updating the area using ajax. So I thought it would be nice to share it:

First, you import your own template tag that you encoded in your view file.

from your_app_name.templatetags import your_tag_name 

And then you use it like this:

 return HttpResponse(your_tag_name.your_method(context)) 

This worked for me, and I received the template tag as a response from the server and updated the div with this result.

+9
source

I had the same question a while ago, I was loading HTML snippets from AJAX, which I already wrote as template tags. And I tried to avoid code duplication in two places.

This is what I came up with to create a template tag from a view (called via ajax):

 from django.template import RequestContext, Template def myview(req): context = RequestContext({'somearg':"FooBarBaz"}) template_string = """ {% load my_tag from tagsandfilters %} {% my_tag somearg %} """ t = Template(template_string) return HttpResponse(t.render(context)) 
+9
source

You can create a template containing only the templatetag template and nothing more. Then you will have in right_side.html:

 {%load cems_templatetags%} {%right_side%} 

and in the view something like:

 if request.isAjax(): return render_to_response('right_side.html',RequestContext(request)) 
0
source

All Articles