Arnold96
Arnold96

Reputation: 123

How can I send a Django Template with Context Variables to an Ajax Call?

How can I send a Django template to an ajax request and include context variables for that template?

Upvotes: 2

Views: 859

Answers (1)

Lord Elrond
Lord Elrond

Reputation: 16032

You can simply use render for this:

def some_ajax_view(request):
    do_stuff()
    ...
    context = {'some_template_variable':'foo'}
    return render(request, 'some_template.html, context)

Now you can access the template in your ajax request:

$.ajax({   
    ...
    success: function(response, status, XHR) {
        console.log(response); // this will print the entire html template
        $('#some-element').append(response); // this will insert the template into "some-element"
    });

If you need to access context variables in your ajax success callback, you can use render_to_string:

from django.template.loader import render_to_string
from django.http import JsonResponse

def some_ajax_view(request):
    do_stuff()
    ...
    context = {'some_template_variable':'foo'}
    html = render_to_string('some_template.html', context)
    print(html) # this will print the entire html template
    return JsonResponse({'html':html, 'context'})

Edit

If you are making a POST request, you need to add a csrf token when the page is initially loaded (not from the ajax view):

def initial_view(request):
    do_stuff()
    return render(request, 'initial_template.html', context)

Now on initial_template.html:

<script type="text/javascript">
window.csrf_token = "{{ csrf_token }}";
</script>

Then, in your ajax call, you need to include it in the request body:

$.ajax({   
  method: 'POST',
  data: {
    csrfmiddlewaretoken: window.csrf_token,
    some_other_data: 'foo',
    ...
  },
  success: function(response, status, XHR) {
  ...

  });

Upvotes: 1

Related Questions