Unable to print the variable passed from view to template

与世无争的帅哥 提交于 2019-12-11 16:38:48

问题


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)

Following is my template-

<!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 ?


回答1:


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.

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.



来源:https://stackoverflow.com/questions/52753628/unable-to-print-the-variable-passed-from-view-to-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!