我正在尝试让 Django 表单从用户输入中捕获数据,获取输入以对 Aylien API 进行 API 调用并在同一页面上显示原始 json 结果。
我能够接受表单输入并成功进行 API 调用并获取要在控制台上打印的 JSON,但是我很难在页面上显示调用的结果。
我不断收到 UnboundLocalError:赋值前引用了局部变量“api_response”错误。下面的代码
模型.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']
View .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>
我显然在这里做错了什么,只是似乎无法弄清楚是什么
最佳答案
您收到此错误是因为您的表单已失效,并且 api_response
只有当表单有效时才会被定义。
要解决您的问题,请更改此:
form = NewsForm(request.POST)
对此:
form = NewsForm(request.POST or None)
如果您制作
GET
根据您的观点,如果您传递一个空的 request.POST
,您的表单将无效。 ,所以你需要通过 None
反而。最后,我建议添加
api_response = None
在您的 else
条款。这将防止 api_response 未定义,并且如果有人篡改表单,您的服务器不会给出 500 错误。
关于django - 获取表单响应,进行 api 调用,然后在 Django 中显示 api 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58295321/