Mutating Algorithm
Mutating Algorithm

Reputation: 2758

Django rest framework: 'create( )' NotImplementedError when making Http POST request

When making a post request in Django I get the error that 'create()' has not been implemented when I did indeed implement it in my serializer file

from rest_framework import serializers
from people.models import People

class PeopleSerializer(serializers.Serializer):
    pk = serializers.IntegerField(read_only=True)
    name = serializers.CharField(max_length=200)
    favoriteCity = serializers.CharField(max_length=200)

    def create(self, validated_data):
        return People.objects.create(**validated_data)

    def update(self, instance, validated_data):
        instance.name = validated_data.get('name', instance.name)
        instance.favoriteCity = validated_data.get(
                                'favoriteCity',instance.favoriteCity)
        instance.save()
        return instance()

Clearly the create method has been implemented and I don't understand why i'm getting a NotImplementedError

Upvotes: 17

Views: 17917

Answers (5)

Vivesh Kumar
Vivesh Kumar

Reputation: 39

Please check your indentation, that 'create' function should be inside that Serializer class, as below example.

class StudentSerializer(serializers.Serializer):
    name = serializers.CharField(max_length=111)
    roll = serializers.IntegerField()
    city = serializers.CharField(max_length=722)

    def create(self,validated_data):
        return Student.objects.create(**validated_data)

Upvotes: 4

Manzar Abbas
Manzar Abbas

Reputation: 7

from rest_framework import serializers from .models import Student

class StudentSerializer(serializers.Serializer): name=serializers.CharField(max_length=555) def create(self,validated_data): return Student.objects.create(**validated_data)enter image description here

Upvotes: -1

Manzar Abbas
Manzar Abbas

Reputation: 7

Please check your indentation, that 'create' function should be within that Serializer class Hopefully it will work.

Upvotes: -1

Hardik Asnani
Hardik Asnani

Reputation: 1

Check if the keys inside data exactly match model attributes when you try to create an object of a particular model using the model serializer

Upvotes: -1

dushyant7917
dushyant7917

Reputation: 654

In your serializer class inherit from ModelSerializer instead of Serializer class since the later doesn't call create() method implicitly.

class PeopleSerializer(serializers.ModelSerializer): 

The above change would do your job!

Upvotes: 48

Related Questions