【问题标题】:django rest framework not return jsondjango rest框架不返回json
【发布时间】:2017-08-21 06:39:51
【问题描述】:

我写了 hello word 程序,想返回 json 格式的数据,但它不起作用。请查看我的代码 网址文件

from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from login import views

urlpatterns = [
    url(r'^hello_world/$', views.hello_world),
]

查看文件

from django.shortcuts import render
from rest_framework import status
from rest_framework.response import Response
from rest_framework.decorators import api_view
# Create your views here.

@api_view()
def hello_world(request, format=None):
    return Response({"message": "Hello, world!"})

http://localhost:8000/login/hello_world/点击网址

得到一个错误

TemplateDoesNotExist at /login/hello_world/

rest_framework/api.html

我想要json格式的数据

【问题讨论】:

    标签: python json django django-rest-framework


    【解决方案1】:

    首先安装 djangorestframework 然后在 settings.py 的已安装应用程序中添加“rest_framework” 示例:`

    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'channels',
        'chat',
        'django_extensions',
        'rest_framework',
        'rest_framework.authtoken',
    ]`
    

    【讨论】:

      【解决方案2】:

      试试http://localhost:8000/hello_world/ 基于 url 模式。 https://docs.djangoproject.com/en/1.10/topics/http/urls/ 每个正则表达式字符串前面的 'r' 是可选的,但建议使用。它告诉 Python 字符串是“原始的”——字符串中的任何内容都不应被转义

      【讨论】:

        【解决方案3】:

        您不需要 Django Rest Framework 来返回如此简单的 Json 数据。如果您只是返回这种形式的数据,请使用JsonResponse

        # views/hello_world.py
        
        from django.http import JsonResponse
        
        def hello_world(request):
            return JsonResponse({'message': 'Hello, world!'})
        

        另一方面,如果你想用 Django Rest Framework 创建一个 API,你最好从他们的tutorial 开始,然后转向更高级的技术。

        【讨论】:

          猜你喜欢
          • 2023-03-25
          • 2014-10-16
          • 2016-06-27
          • 2016-05-03
          • 2021-08-14
          • 1970-01-01
          • 2018-06-30
          • 2016-04-29
          • 2016-05-03
          相关资源
          最近更新 更多