2

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

2
  • Can you explain a bit more what are you trying to achieve? Commented Oct 9, 2019 at 7:55
  • Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. Commented Oct 9, 2019 at 7:57

1 Answer 1

1

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) {
  ...

  });
Sign up to request clarification or add additional context in comments.

1 Comment

How can i include csrf token?. I get this error: Forbidden (CSRF token missing or incorrect

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.