I am facing an issue when testing my EventViewSet. I get the following error
TypeError: Field 'facebook_reactions' expected a number but got <class 'rest_framework.fields.IntegerField'>.
This is the test I ran:
class EventViewSetTest(BaseTestCase):
def test_event_created(self):
event_data = {
"url": "www.example.com",
"tweet_text": "Event successful",
"facebook_reactions": 2,
}
response = self.client.post("/api/events/", event_data)
self.assertEqual(status.HTTP_201_CREATED,response.status_code)
Here is my views.py:
class EventViewSet(ModelViewSet):
queryset = Event.objects.all()
def get_serializer_class(self):
if self.action == "create":
return serializers.EventCreateSerializer
return serializers.EventSerializer
def perform_create(self, serializer):
Event.objects.create(
url=Link.objects.get_or_create(url=serializer.url)[0],
tweet_text=serializer.tweet_text,
facebook_reactions=serializer.facebook_reactions,
)
Here is my serializers.py:
class EventCreateSerializer(serializers.Serializer):
url = serializers.URLField
tweet_text = serializers.CharField
facebook_reactions = serializers.IntegerField
class EventSerializer(serializers.ModelSerializer):
class Meta:
model = Event
fields = ["url", "tweet_text", "facebook_reactions"]
Help would be much appreciated.
Thank you!
CodePudding user response:
You need to call the constructors of the fields, so:
class EventCreateSerializer(serializers.Serializer):
url = serializers.URLField()
tweet_text = serializers.CharField()
facebook_reactions = serializers.IntegerField()
as for the perform_create
, you need to work with the data.validated_data
, so:
class EventViewSet(ModelViewSet):
# …
def perform_create(self, serializer):
data = serializer.validated_data
Event.objects.create(
url=Link.objects.get_or_create(url=data['url'])[0],
tweet_text=data['tweet_text'],
facebook_reactions=data['facebook_reactions'],
)