【发布时间】:2019-10-08 23:51:12
【问题描述】:
我正在尝试让 Django 表单从用户输入中捕获数据,获取输入以对 Aylien API 进行 API 调用,并在同一页面上显示原始 json 结果。
我能够接受表单输入并成功进行 API 调用并让 JSON 在控制台上打印,但我很难在页面上显示调用的结果。
我不断收到 UnboundLocalError: local variable 'api_response' referenced before assignment 错误。代码如下
models.py
from django.db import models
# Create your models here.
class News(models.Model):
title = models.TextField(max_length=120)
form.py
from django import forms
from .models import News
class NewsForm(forms.ModelForm):
class Meta:
model = News
fields = [
'title']
views.py
from django.shortcuts import render
from .models import News
from .form import NewsForm
import requests
import aylien_news_api
from aylien_news_api.rest import ApiException
def news_create_view(request):
## link form to model for gathering search term from user
form = NewsForm(request.POST)
if form.is_valid():
# create an instance of the aylien api class
api_instance = aylien_news_api.DefaultApi()
## build opts for api call from the response from the user
opts = {
'title': form.cleaned_data['title'],
'language': ['en'],
'not_language': ['es', 'it'],
'published_at_start': 'NOW-7DAYS',
'published_at_end': 'NOW'
}
try:
# List the stories
api_response = api_instance.list_stories(**opts)
except ApiException as e:
print("Exception when calling DefaultApi->list_stories: %s\n" % e)
## re-instantiate the form and save to admin
form.save()
form = NewsForm()
else:
form = NewsForm()
## context for models
context = {
'form': form,
'api_response': api_response
}
## render pages in Django dynamically (static HTML is slow to load)
return render(request, "news/show_result.html", context)
show_result.html
<div class="row">
<form method="GET"> {% csrf_token %}
<!-- the 'as_p' method turns the django-rendered form into html for the user -->
{{ form.as_p }}
<input type="submit", value="Search" />
</form>
</div>
<div class="row">
{{ api_response }}
</div>
我显然在这里做错了什么,只是似乎无法弄清楚是什么
【问题讨论】:
标签: django django-models django-forms