Вы можете просто использовать render
для этого:
def some_ajax_view(request):
do_stuff()
...
context = {'some_template_variable':'foo'}
return render(request, 'some_template.html, context)
Теперь вы можете получить доступ к шаблону в вашем запросе ajax:
$.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"
});
Если вам нужен доступ к переменным контекста вВаш успешный обратный вызов ajax, вы можете использовать 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'})
Редактировать
Если вы делаете запрос POST
, вам нужно добавить csrfмаркер при начальной загрузке страницы ( не из представления ajax):
def initial_view(request):
do_stuff()
return render(request, 'initial_template.html', context)
Теперь на initial_template.html
:
<script type="text/javascript">
window.csrf_token = "{{ csrf_token }}";
</script>
Затем в вашем Ajaxпозвоните, вам нужно включить его в тело запроса:
$.ajax({
method: 'POST',
data: {
csrfmiddlewaretoken: window.csrf_token,
some_other_data: 'foo',
...
},
success: function(response, status, XHR) {
...
});