How can I send a Django template to an ajax request and include context variables for that template?
-
Can you explain a bit more what are you trying to achieve?Dev Catalin– Dev Catalin2019-10-09 07:55:16 +00:00Commented 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.user8060120– user80601202019-10-09 07:57:19 +00:00Commented Oct 9, 2019 at 7:57
Add a comment
|
1 Answer
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) {
...
});
1 Comment
Arnold96
How can i include csrf token?. I get this error: Forbidden (CSRF token missing or incorrect