我正在使用 djangorestframework、django 2.1.4 和 python 3.6+ 我有一个简单的模型,我试图通过使用requests
. 即使我通过 json 格式传递数据,它也会给我一个 415 错误。我需要做什么来修复它?
模型.py
class Card(models.Model):
id = models.CharField(max_length=36, blank=False, primary_key=True)
card_title = models.CharField(max_length=100, blank=False)
序列化程序.py
from rest_framework import serializers
class CardSerializer(serializers.ModelSerializer):
class Meta:
model = Card
fields = ('id', 'card_title',)
视图.py
from cards.models import Card
from cards.serializers import CardSerializer
from rest_framework import generics
from rest_framework import permissions
class CardList(generics.ListCreateAPIView):
permission_classes = ()
queryset = Card.objects.all()
serializer_class = CardSerializer
class CardDetail(generics.RetrieveUpdateDestroyAPIView):
permisssion_classes = () # set the permission class
queryset = Card.objects.all()
serializer_class = CardSerializer
网址.py
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from cards import views
urlpatterns = [
path('cards/', views.CardList.as_view()),
path('cards/<int:pk>/', views.CardDetail.as_view()),
]
urlpatterns = format_suffix_patterns(urlpatterns)
最后,这是我用来更新它的脚本
import json
import requests # http requests
BASE_URL = "http://127.0.0.1:8000/"
ENDPOINT = "cards/"
def create_update():
new_data = {
'id': 3,
"card_title": "AA"
}
r = requests.post(BASE_URL + ENDPOINT, data=json.dumps(new_data))
print(r.headers)
if r.status_code == requests.codes.ok:
return r.json()
return r.text
create_update()
有趣的是,我可以new_data
在脚本中使用 djangorestframework 工具在原始数据部分下使用媒体类型 application/json 发布它。
这是请求标头 -
{'Date': 'Sun, 30 Dec 2018 17:53:33 GMT', 'Server': 'WSGIServer/0.2 CPython/3.6.6', 'Content-Type': 'application/json', 'Vary': 'Accept, Cookie', 'Allow': 'GET, POST, HEAD, OPTIONS', 'X-Frame-Options': 'SAMEORIGIN', 'Content-Length': '62'}
这里发生了什么?