Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Template Tags in Views

Hi I need to refresh my custom template tag --right_side.py-- via Ajax. Is there a way to import the template tag in the view and return it as HttpResponse because I don't want to give up my custom template tag (it works great in other pages) nor code a new view action which is really similar to it.

Having a link to call with Ajax or loading it in the view inside

if request.isAjax():

Are both fine for me.

like image 384
Cem Baykam Avatar asked Feb 21 '11 16:02

Cem Baykam


2 Answers

I had this same question awhile ago, I was loading HTML snippets with AJAX which I had already written as template tags. And I was trying to avoid duplicating the code in two places.

This is what I came up with to render 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))
like image 50
David Lam Avatar answered Oct 06 '22 21:10

David Lam


I find it really useful when refreshing an area with ajax. So thought it would be good to share it:

First you import the custom template tag you coded 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))

That worked for me and I got the template tag as response from server and refreshed the div with that result.

like image 32
Cem Baykam Avatar answered Oct 06 '22 20:10

Cem Baykam