Atma
Atma

Reputation: 29767

append a django template include with jquery

I want to add the following django template include, which is a list item, to a UL called myClass after a jquery post:

 $.post(url,data,function(result){
        $( ".myClass" ).append('{% include "mytemplate.html" %}');
        })

This results in an error that reloads the page.

I have read about jquery load and it sounds promising. Either way how do I add the list item?

Upvotes: 2

Views: 2290

Answers (2)

suhailvs
suhailvs

Reputation: 21690

it is not possible to do $( ".myClass" ).append('{% include "mytemplate.html" %}');

the one of the possible way is:

<form action="#" method="post" id="testForm">     
    <input type="text" name="tester" value="">        
    <input type="submit" value="save" />
</form>
<div class="myClass"></div>

script

$("#testForm").on("submit", function(event){    
    $.post('url', $(this).serialize(),
    function(data){
        CreateRow(data);
    }, "json"); 
    event.preventDefault(); 
});

function CreateRow(dd){
    $(".myClass").append(dd.mycontent);
}

views.py for url

import json
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def testpost(request):
    str_html="""
    <h1>....</h1>...your full htmlcode
    """       
    return HttpResponse(json.dumps({"mycontent": str_html}), mimetype="application/json")

Upvotes: 0

Victor Castillo Torres
Victor Castillo Torres

Reputation: 10811

The most similar way to do this is that in a view you return the template already rendered for example you have a template named to_include.html:

The template to_include.html

<p>{{variable}}</p>

The URL

url(r'^some_view/$', some_view),

The POST request (in the template where you will include to_include.html)

 $.post('/some_view/',data,function(result){
        $( ".myClass" ).append(result);
        }, 'html');

The VIEW

def some_view(request):
    variable = "Hi I am an example"
    return render(request, 'to_include.html', {'variable': variable})

The logic is that the view (some_view) will return the template (to_include.html) already rendered to the POST request:

    <p>Hi I am an example</p>

so result will be the template already rendered and :

$( ".myClass" ).append(result);

really is:

$( ".myClass" ).append("<p>Hi I am an example</p>");

Upvotes: 2

Related Questions