【问题标题】:Taking a form response, making an api call then displaying the api call in Django获取表单响应,进行 api 调用,然后在 Django 中显示 api 调用
【发布时间】: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


    【解决方案1】:

    您收到此错误是因为您的表单无效,并且只有在表单有效时才会定义api_response

    要解决您的问题,请更改以下内容:

    form = NewsForm(request.POST)
    

    到这里:

    form = NewsForm(request.POST or None)
    

    如果你在视图中添加GET,如果你传递一个空的request.POST,你的表单将无效,所以你需要传递None

    最后,我建议在您的 else 子句中添加 api_response = None。这将防止 api_response 永远未定义,并且如果有人篡改表单,您的服务器不会给出 500 错误。

    【讨论】:

    • 如此简单!知道这是一个愚蠢的错误。非常感谢 :) 祝你有美好的一天
    猜你喜欢
    • 2019-12-22
    • 1970-01-01
    • 1970-01-01
    • 2020-02-02
    • 2018-01-29
    • 1970-01-01
    • 2018-07-13
    • 2019-10-30
    • 1970-01-01
    相关资源
    最近更新 更多