我已經使用djangorestframework創建了一個API,但是當我在終端中使用python manage.py runserver命令時,它顯示「HTTP/1.0 301 Moved Permanently」錯誤。 This the Message which it showsHTTP/1.0 301永久移動 - Django
但很酷的是,當我在瀏覽器中運行它顯示數據。 This the result in Chrome
我想知道發生了它。
而在此POST調用也不起作用。
下面是代碼:
serializers.py
from rest_framework import serializers
from snippets.models import Snippet
class SnippetSerializer(serializers.ModelSerializer):
class Meta:
model = Snippet
fields = ('title','code',)
def create(self, validated_data):
return Snippet.objects.create(**validated_data)
def update(self, instance, validated_data):
instance.title = validated_data.get('title', instance.title)
instance.code = validated_data.get('code', instance.code)
instance.save()
return instance
Views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
# Create your views here.
class JSONResponse(HttpResponse):
def __init__(self,data,**kwargs):
content = JSONRenderer().render(data)
kwargs['content_type']='application/json'
super(JSONResponse, self).__init__(content, **kwargs)
@csrf_exempt
def snippet_list(request):
"""
List all code snippets, or create a new snippet.
"""
if request.method == 'GET':
snippets = Snippet.objects.all()
serializer = SnippetSerializer(snippets, many=True)
return JSONResponse(serializer.data)
elif request.method == 'POST':
data = JSONParser().parse(request)
serializer = SnippetSerializer(data=data)
if serializer.is_valid():
serializer.save()
return JSONResponse(serializer.data, status=201)
return JSONResponse(serializer.errors, status=400)
@csrf_exempt
def snippet_detail(request, pk):
"""
Retrieve, update or delete a code snippet.
"""
try:
snippet = Snippet.objects.get(pk=pk)
except Snippet.DoesNotExist:
return HttpResponse(status=404)
if request.method == 'GET':
serializer = SnippetSerializer(snippet)
return JSONResponse(serializer.data)
elif request.method == 'PUT':
data = JSONParser().parse(request)
serializer = SnippetSerializer(snippet, data=data)
if serializer.is_valid():
serializer.save()
return JSONResponse(serializer.data)
return JSONResponse(serializer.errors, status=400)
elif request.method == 'DELETE':
snippet.delete()
return HttpResponse(status=204)
Models.py
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Snippet(models.Model):
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=100, blank=True, default='')
code = models.TextField()
class Meta:
ordering = ('created',)
非常感謝@koniiiik,它的工作 –
但@ koniiiik我無法職位上給它的數據,使用郵遞員 –
您需要發佈到包含結尾斜槓的URL,沒有斜槓的URL將始終返回重定向,並忽略請求主體。 – koniiiik