I'm using djangorestframework, django 2.1.4, and python 3.6+
I have a simple model that I'm trying to add via a script that uses requests
. Even though I'm passing in the data via a json format, it is giving me a 415 error. What do I need to do to fix it?
models.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)
serializers.py
from rest_framework import serializers
class CardSerializer(serializers.ModelSerializer):
class Meta:
model = Card
fields = ('id', 'card_title',)
views.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
urls.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)
finally, here's the script that I am using to update it
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()
The funny thing is, that I can take the new_data
in the script and post that just fine via the djangorestframework tool under the raw data section with media type application/json.
Here's the request header -
{'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'}
What is happening here?