-1

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?

Micah Pearce
  • 1,805
  • 3
  • 28
  • 61
  • Possible duplicate of [Http 415 Unsupported Media type error with JSON](https://stackoverflow.com/questions/22566433/http-415-unsupported-media-type-error-with-json) – Red Cricket Dec 30 '18 at 18:05
  • I saw that, but that's in javascript and so idk what's going on there. – Micah Pearce Dec 30 '18 at 18:44

1 Answers1

1

In the script I'm running, I have the code data=json.dumps(new_data). It needs to be changed to data=new_data. Then it works perfectly.

Micah Pearce
  • 1,805
  • 3
  • 28
  • 61