我有一个获取用户输入的表单,我将其传递给view.py上的python脚本,然后呈现为html模板。我希望完成所有这些操作而不刷新页面。
view.py:
def index(request):
if request.method == 'POST':
form = PnrForm(request.POST)
if form.is_valid():
pnr_numbers = form.cleaned_data['pnr_number']
api_key = "df566"
base_url = "https://api.railwayapi.com/v2/pnr-status/pnr/"
complete_url = base_url + pnr_numbers + "/apikey/" + api_key + "/"
response_ob = requests.get(complete_url)
output = response_ob.json()
if output["response_code"] == 200:
train_name = output["train"]["name"]
passengers_list = output["passengers"]
aka = "this is the"
for passenger in passengers_list:
# store the value or data
# of "no" key in variable
passenger_num = passenger["no"]
# store the value or data of
# "current_status" key in variable
current_status = passenger["current_status"]
# store the value or data of
# "booking_status" key in variable
booking_status = passenger["booking_status"]
# print following values
print(" passenger number : " + str(passenger_num)
+ "\n current status : " + str(current_status)
+ "\n booking_status : " + str(booking_status))
aka = str(passenger_num)
else:
print("record is not found for given request")
return render(request, 'main_site/index.html', {'form': form,'output': aka})
else:
form = PnrForm()
#print(pnr_numbers)
return render(request, 'main_site/index.html', {'form': form})
index.html:
<form method="POST" id="pnr_form">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-4">
<div class="box">
<div class="box-icon">
<img src="images/service-icon-1.png" alt="">
</div>
<h4>{{ output }}</h4>
</div>
</div>
<script type="text/javascript">
$(document).on('submit','#pnr_form',function(e){
e.preventDefault();
$.ajax({
type:'POST',
url: '',
data:{
pnr_number:$('pnr_form').val(),
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success:function(){
alert('pnr submitted')
}
});
});
</script>
它正在提交表单,但未在html模板上呈现..................................... ..................................