简体   繁体   English

django rest 框架不返回 json

[英]django rest framework not return json

I have writen hello word programme and want to return json format data but it does not working.我已经编写了 hello word 程序,想返回 json 格式的数据,但它不起作用。 Please look into my code URL file请查看我的代码 URL 文件

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),
]

View file查看文件

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/ hit a url http://localhost:8000/login/hello_world/点击一个 url

get an error得到一个错误

TemplateDoesNotExist at /login/hello_world/

rest_framework/api.html

i want this data in json format我想要json格式的数据

You don't need Django Rest Framework to return Json data that are so simple.你不需要 Django Rest Framework 来返回如此简单的 Json 数据。 If you're just returning such form of data use JsonResponse .如果您只是返回这种形式的数据,请使用JsonResponse

# views/hello_world.py

from django.http import JsonResponse

def hello_world(request):
    return JsonResponse({'message': 'Hello, world!'})

On the other hand, if you want to create an API with Django Rest Framework, you should better start with their tutorial and then move on to more advanced techniques.另一方面,如果你想用 Django Rest Framework 创建一个 API,你最好从他们的 教程开始,然后转向更高级的技术。

Try http://localhost:8000/hello_world/ based on url patern.根据 url 模式尝试http://localhost:8000/hello_world/ https://docs.djangoproject.com/en/1.10/topics/http/urls/ The 'r' in front of each regular expression string is optional but recommended. https://docs.djangoproject.com/en/1.10/topics/http/urls/每个正则表达式字符串前面的 'r' 是可选的,但建议使用。 It tells Python that a string is “raw” – that nothing in the string should be escaped它告诉 Python 一个字符串是“原始的”——字符串中的任何内容都不应该被转义

first install djangorestframework then add 'rest_framework' in Installed app in settings.py Example:`首先安装 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',
]`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM