Render ajax post to HTML in Django with render_to_string

Viewed 1045

I am writing an page that with a form of several inputs wrapped in selectize.js on the top. By clicking a button, I wish to return some queries info based on inputs. I am using ajax to post inputs to avoid page reloading.

I am following DJANGO render new result values from AJAX request to HTML page to render the queried result cat_result based on ajax post data in HTML.

def cat_select(request):
    cat_result=[]
    cat_selected=[]
    cat_name=['l2','l3']
    cat_selected=list(map(lambda x:request.POST.get(x, '').split(','), cat_name))
    cat_result=c_result(["US"],cat_selected) #list of tuples I want to get 
    print(cat_selected)
    print(cat_result)
    html=render_to_string(request, 'esearch/result.html', {'cat_result': cat_result})
    return JsonResponse({'cat':cat_result,'html':html},safe=False)

But I get below error on render_to_string

  File "C:\Users\AppData\Local\Continuum\anaconda3\lib\site-packages\django\template\loaders\base.py", line 18, in get_template
    for origin in self.get_template_sources(template_name):
  File "C:\Users\AppData\Local\Continuum\anaconda3\lib\site-packages\django\template\loaders\filesystem.py", line 36, in get_template_sources
    name = safe_join(template_dir, template_name)
  File "C:\Users\AppData\Local\Continuum\anaconda3\lib\site-packages\django\utils\_os.py", line 32, in safe_join
    final_path = abspath(join(base, *paths))
  File "C:\Users\AppData\Local\Continuum\anaconda3\lib\ntpath.py", line 115, in join
    genericpath._check_arg_types('join', path, *paths)
  File "C:\Users\AppData\Local\Continuum\anaconda3\lib\genericpath.py", line 149, in _check_arg_types
    (funcname, s.__class__.__name__)) from None
TypeError: join() argument must be str or bytes, not 'WSGIRequest'

There is the function that works with the main base.html which result.html extend from.

def search_index(request):
    ##something to populate input options for l2 and l3
    print(results)
    context = {'l2':l2, 'l3':l3}
    return render(request, 'esearch/base.html', context) 

base.html

<form id="cat_select">{% csrf_token %} 
<input class="site" name="site" type="text">
<input class="l2" name="l2" id="l2" type="text" style="width:30%">
<input class="l3" name="l3" id="l3" type="text" style="width:50%">
<br>
<button class="btn btn-outline-success my-2 my-sm-0" type="submit" id="cat_submit">Submit</button>
</form>
<script type="text/javascript">
$(document).on('submit','#cat_select',function(e){
    e.preventDefault();
    $.ajax({
        type:'POST',
        url:'/cat_select',
        data:{
            l2:$('#l2').val(),
            l3:$('#l3').val(),
            csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
        },
        success: function(){
            alert ("selected!")
        }
    });
});
</script>

result.html

{% extends "esearch/base.html" %}
{% block title %} Result {% endblock %}
{% block content %}
{% load staticfiles %}
<!doctype html>
<html>
{% if cat_result %}
    {{cat_result}} 
{%elif not cat_result %}
    <p>No cat_result </p>
{% endif %}
</body>     
</html>
{% endblock %}

Am I on the correct path to pass queried info to HTML? If so, how to solve the error? Thanks.

1 Answers

You're incorrectly calling render_to_string. If you look at the function documentation, you'll see that the expected order of positional arguments is template_name, context, request. You're passing in request first, so the function expects a string when you've passed a WSGIRequest object, as the error states.

Fix this error by replacing:

html = render_to_string(request, 'result.html', {'cat_result': cat_result})

with:

html = render_to_string('result.html', {'cat_result': cat_result}, request)

or by explicitly naming the arguments:

html = render_to_string(request=request, template_name='result.html', context={'cat_result': cat_result})
Related