1from rest_framework import serializers
2
3class PostSerializer(serializers.ModelSerializer):
4 user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault())
5 class Meta:
6 model = Post
1serializer = CommentSerializer(data={'email': 'foobar', 'content': 'baz'})
2serializer.is_valid()
3# False
4serializer.errors
5# {'email': ['Enter a valid e-mail address.'], 'created': ['This field is required.']}
1class EventSerializer(serializers.ModelSerializer):
2
3 class Meta:
4 model = models.Event
5 exclude = ['user']
6
7
8class EventView(APIView):
9
10 def post(self, request):
11 es = EventSerializer(data=request.data)
12 if es.is_valid():
13 es.save(user=self.request.user)
14 return Response(status=status.HTTP_201_CREATED)
15 return Response(data=es.errors, status=status.HTTP_400_BAD_REQUEST)
1class Event(models.Model):
2 user = models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
3 date = models.DateTimeField(default=timezone.now)
4 place = models.CharField(max_length=255)