JSONDecodeError at / Expecting value: line 1 column 1 (char 0) when try to return response in a django rest_framework
JSONDecodeError at / Expecting value: line 1 column 1 (char 0) when try to return response in a django rest_framework
我是 python rest_framework
的新手。我正在尝试创建一个包含两个 App
的 django
网站。
第一个 App 有一个 HTML 表单 ,它从用户那里获取城市名称,然后向 发送请求第二个 App 中的 API 调用 WeatherApp
。在 WeatherApp
中,我从数据库中读取数据并将其序列化,但是当尝试 return response
时,我收到此错误:
JSONDecodeError at /
Expecting value: line 1 column 1 (char 0)
这是第一个应用views
:
def index(request):
context = {'form': form}
if request.method == 'POST':
form = CityForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
url = "http://127.0.0.1:8000/city/{}"
city_weather = requests.get(url.format(name)).json()
这是 WeatherApp
views
:
def myfunc(self, cityname):
query = City.objects.filter(name = cityname)[0]
serializer = CitySerializer(query)
return Response(serializer.data)
如有任何帮助,我们将不胜感激。
我弄明白了,并与有类似问题的任何人分享解决方案:
问题出在 WeatherApp
views
的 return
中。
应该是这样的:
return JsonResponse(serializer.data)
和 JsonResponse
应该像这样导入:
from django.http import JsonResponse
我是 python rest_framework
的新手。我正在尝试创建一个包含两个 App
的 django
网站。
第一个 App 有一个 HTML 表单 ,它从用户那里获取城市名称,然后向 发送请求第二个 App 中的 API 调用 WeatherApp
。在 WeatherApp
中,我从数据库中读取数据并将其序列化,但是当尝试 return response
时,我收到此错误:
JSONDecodeError at / Expecting value: line 1 column 1 (char 0)
这是第一个应用views
:
def index(request):
context = {'form': form}
if request.method == 'POST':
form = CityForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
url = "http://127.0.0.1:8000/city/{}"
city_weather = requests.get(url.format(name)).json()
这是 WeatherApp
views
:
def myfunc(self, cityname):
query = City.objects.filter(name = cityname)[0]
serializer = CitySerializer(query)
return Response(serializer.data)
如有任何帮助,我们将不胜感激。
我弄明白了,并与有类似问题的任何人分享解决方案:
问题出在 WeatherApp
views
的 return
中。
应该是这样的:
return JsonResponse(serializer.data)
和 JsonResponse
应该像这样导入:
from django.http import JsonResponse