无法打印从视图传递到模板的变量 [英] Unable to print the variable passed from view to template
问题描述
我正在尝试将变量传递,我从视图获取模板,但是该变量显示在网络浏览器(chrome)的预览中,但未显示在实际屏幕上。
以下是我的视图文件:
I am trying to pass the variable ,I am obtaining from view to the template but it is showing in the preview of the web-browser(chrome) but not on actual screen. Following is my view file:
analyzer=SentimentIntensityAnalyzer()
data={}
with open('today_5th_oct_new.csv','r',newline='', encoding='utf-8') as f:
reader = csv.reader(f)
for row in reader:
data[row[0]]=float(row[1])
analyzer.lexicon.update(data)
def index(request):
return render(request, "gui/index.html")
@csrf_exempt
def output(request):
sentences = request.POST.get('name',None)
senti = analyzer.polarity_scores(sentences)
context_dict = {'sentiment': senti}
return render(request,"gui/index.html", context = context_dict)
以下是我的模板-
<!doctype html>
<html>
<head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></head>
<body>
<form action>
Enter Sentence:<input id = "name" type = "text" name = "EnterSentence" encoding = "utf-8"><br>
<input onclick = "testfunction()" type = "button" value = "Submit" >
</form>
<div><strong>Score is {{ sentiment }}</strong></div>
</body>
<script>
var testfunction = () => {
var test = document.getElementById("name").value
console.log(test)
$.ajax({
type: "POST",
dataType: "json",
url: 'output/',
data:{
csrfmiddlewaretoken: '{{ csrf_token }}',
'name': test
},
success: function(response) {
console.log("Succesful return firm ajax call");
},
error: function(result){
console.log("Failure");
}
});
}
</script>
我正在观察所需的输出在预览中,但不在实际页面上。
如何解决?
I am observing the desired output in preview but not on actual page. How to resolve that ?
推荐答案
您正在通过Ajax获得响应,但是您对此没有做任何事情。您的成功
函数需要以某种方式将内容插入页面。
You're getting the response via Ajax but you're not doing anything with it. Your success
function needs to insert the content into the page somehow.
老实说,我看不到为什么在这里完全使用Ajax?如果您删除了JS代码,只是让您的表单直接执行POST,那么它将正常工作。
To be honest, I don't see why you use Ajax here at all; if you removed the JS code and just let your form do a POST directly it would work fine.
这篇关于无法打印从视图传递到模板的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!