Skip to main content
 首页 » 编程设计

python之使用 render_to_string 在 Django 中将 ajax post 渲染为 HTML

2024年08月12日52zhenyulu

我正在编写一个页面,该页面的顶部包含一些包含在 selectize.js 中的输入。通过单击一个按钮,我希望根据输入返回一些查询信息。我正在使用 ajax 发布输入以避免页面重新加载。

我正在关注 DJANGO render new result values from AJAX request to HTML page根据 HTML 中的 ajax 发布数据呈现查询结果 cat_result。

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) 

但我在 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' 

有一个函数可以与 result.html 扩展的主要 base.html 一起使用。

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)  

基础.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> 

结果.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 %} 

我是否在将查询信息传递到 HTML 的正确路径上?如果是这样,如何解决错误?谢谢。

请您参考如下方法:

您错误地调用了 render_to_string。如果您查看 function documentation ,您会看到位置参数的预期顺序是 template_name、context、request。您首先传递请求,因此当您传递 WSGIRequest 对象时,该函数需要一个字符串,如错误状态。

通过替换来修复此错误:

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

与:

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

或通过显式命名参数:

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