将python脚本结果输出到html模板中

时间:2019-05-23 07:06:43

标签: html django python-3.x

我已经用django设置了所有内容,并且有一个带有表单的html模板,因为您可以看到此表单获取pnr编号,然后运行python脚本并输出json结果,现在如何在我的index.html模板上获取此结果无需重新加载页面。

<header class="header-area overlay full-height relative v-center" id="home-page">
    <div class="absolute anlge-bg"></div>
    <div class="container">
        <div class="row v-center">
            <div class="col-xs-12 col-md-7 header-text">
                <h2>It’s all about Promoting your Business</h2>
                <form method="POST"> 
                {% csrf_token %}
                {{ form }}
                <input type="submit" value="Submit">

                </form>
            </div>

            </div>
        </div>
    </div>
</header>

view.py:

from django.shortcuts import redirect,render
from django.http import HttpResponseRedirect
from .forms import PnrForm
import requests, json


def index(request):
  if request.method == 'POST':
     form = PnrForm(request.POST)
     if form.is_valid():
        pnr_numbers = form.cleaned_data['pnr_number']
        api_key = "apikey"

        base_url = "https://api.railwayapi.com/v2/pnr-status/pnr/"

        # Enter valid pnr_number 
        #pnr_number = "pnrnumber"

        # Stores complete url address 
        complete_url = base_url + pnr_number + "/apikey/" + api_key + "/"

        # get method of requests module 
        # return response object 
        response_ob = requests.get(complete_url) 

       # json method of response object convert 
       # json format data into python format data 
        result = response_ob.json() 


        else:
          form = PnrForm()

  return render(request, 'main_site/index.html', {'form': form, 'result':result }) 

每当我运行此结果时,未定义该结果,因为它超出范围

但是当我运行它时:

def index(request):
if request.method == 'POST':
    form = PnrForm(request.POST)

    if form.is_valid():
        pnr_numbers = form.cleaned_data['pnr_number']


        #print(result)
        #tboss = "this is new"
        #return HttpResponseRedirect('/thanks')


else:
    form = PnrForm()

api_key = "apikey"

base_url = "https://api.railwayapi.com/v2/pnr-status/pnr/"

# Enter valid pnr_number 
        # pnr_number = "pnrnumber"

# Stores complete url address 
complete_url = base_url + pnr_numbers + "/apikey/" + api_key + "/"

# get method of requests module 
# return response object 
response_ob = requests.get(complete_url) 

# json method of response object convert 
# json format data into python format data 
result = response_ob.json() 

#print(json.dumps)
return render(request, 'main_site/index.html', {'form': form, 'result':result })

它显示错误pnr_numbers未被定义为其非本地变量 任何建议我如何在上下文中传递输出

0 个答案:

没有答案