You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django视图API返回用户输入报错,求代码修正与模板指导

问题解决与代码修正

核心错误原因及修复

1. 'WSGIRequest' object has no attribute 'request' 错误

你把视图函数的参数名写成了requests,和调用API用的requests库重名了。Django把WSGI请求对象传给这个参数后,再调用requests.request()时,实际是在操作WSGIRequest对象而非requests库,所以触发报错。

修正: 把视图函数的参数名改成Django标准的request,确保导入requests库(没导入的话加import requests)。

2. 获取用户输入并替换querystring的'q'值

当前代码里search = 'POST'根本没获取用户输入,querystring[0] = search也是错误写法(字典不能用索引访问)。正确做法是从POST请求里拿到用户输入的内容,再赋值给querystring的'q'键。

修正:

search = request.POST.get('search', '')  # 从表单取输入,默认空字符串
querystring = {"q": f"*{search}*", "hl":"en","gl":"US"}  # 直接替换q的值

3. news.html的h1语法错误

{{news.views}}是无效模板变量,你需要把API返回的数据传给模板,再在模板里正确引用。

修正:

  • 视图里传数据到模板:return render(request, 'news.html', {'news_data': response.json()})
  • news.html里改成{{ news_data }}(可根据API返回结构调整,比如取具体字段{{ news_data.some_key }})

4. 表单代码错误

index.html的form标签写法混乱,属性要放在标签内,action应该用Django的url模板标签,且form标签未闭合。

修正:

<form class="form-inline" method="POST" action="{% url 'news' %}" name="news">
  <div class="input-group mb-3">
    {% csrf_token %}
    <input
      type="text"
      class="form-control"
      placeholder="Enter Crypto"
      name="search"
      style="width: 50%; display: block; margin: 0 auto"
    />
    <button
      class="btn btn-outline-primary btn-md"
      type="submit"
      id="button-addon2"
    >
      Search
    </button>
  </div>
</form>

5. 路由冲突问题

mysite/urls.py里同时写了path('', include('search.urls'))和path('news/', include('search.urls')),会导致路由重复(比如/news/news/也能匹配到news视图)。

修正: 只保留path('', include('search.urls')),因为someapp/urls.py里已经定义了news/路径。

完整修正后的代码

views.py

import requests
from django.shortcuts import render
from django.http import HttpResponse

def index(request):
    return render(request, 'index.html')

def news(request): 
    if request.method == 'POST':
        search = request.POST.get('search', '')
        url = "https://google-finance4.p.rapidapi.com/search/"
        querystring = {"q": f"*{search}*", "hl":"en","gl":"US"}

        headers = {
            "X-RapidAPI-Key": "my api key",
            "X-RapidAPI-Host": "google-finance4.p.rapidapi.com"
        }

        response = requests.request("GET", url, headers=headers, params=querystring)
        print(response.text)
        return render(request, 'news.html', {'news_data': response.json()})
    else:
        return HttpResponse('Error')

someapp/urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='home'),
    path('news/', views.news, name="news")
]

mysite/urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('search.urls')), 
]

templates/index.html

<form class="form-inline" method="POST" action="{% url 'news' %}" name="news">
  <div class="input-group mb-3">
    {% csrf_token %}
    <input
      type="text"
      class="form-control"
      placeholder="Enter Crypto"
      name="search"
      style="width: 50%; display: block; margin: 0 auto"
    />
    <button
      class="btn btn-outline-primary btn-md"
      type="submit"
      id="button-addon2"
    >
      Search
    </button>
  </div>
</form>

templates/news.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Crypto Talk</title>
</head>
<body>
  <h1>{{ news_data }}</h1>
</body>
</html>

内容的提问来源于stack exchange,提问作者drafty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 15:19:21