【问题标题】:Render ajax post to HTML in Django with render_to_string使用 render_to_string 在 Django 中将 ajax 帖子渲染为 HTML
【发布时间】:2020-02-10 09:13:40
【问题描述】:

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

我正在关注DJANGO render new result values from AJAX request to HTML page根据HTML中的ajax post数据渲染查询结果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'

有一个函数适用于主base.htmlresult.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) 

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>

结果.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?如果是这样,如何解决错误?谢谢。

【问题讨论】:

    标签: python django


    【解决方案1】:

    您错误地调用了render_to_string。如果您查看function documentation,您会看到位置参数的预期顺序是template_namecontextrequest。您首先传递请求,因此当您传递 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})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-03
      • 1970-01-01
      • 2010-11-25
      • 2020-07-31
      • 1970-01-01
      • 2018-06-09
      • 2020-01-12
      • 2020-04-12
      相关资源
      最近更新 更多