【发布时间】: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.html,result.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?如果是这样,如何解决错误?谢谢。
【问题讨论】: