Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

pass user to serializer django rest framework

class CommentSerializer(serializers.Serializer):
    ...

    def create(self, validated_data):
      user = self.context['request'].user
      comment = Comment.objects.create(
         user=user, 
         **validated_data
      )
      return comment
Comment

User serializer in django rest framework

from rest_framework import serializers

class PostSerializer(serializers.ModelSerializer):
    user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault())
    class Meta:
        model = Post
Comment

User serializer in django rest framework

class EventSerializer(serializers.ModelSerializer):

    class Meta:
        model = models.Event
        exclude = ['user']


class EventView(APIView):

    def post(self, request):
        es = EventSerializer(data=request.data)
        if es.is_valid():
            es.save(user=self.request.user)
            return Response(status=status.HTTP_201_CREATED)
        return Response(data=es.errors, status=status.HTTP_400_BAD_REQUEST)
Comment

User serializer in django rest framework

class Event(models.Model):
    user = models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    date = models.DateTimeField(default=timezone.now)
    place = models.CharField(max_length=255)
Comment

PREVIOUS NEXT
Code Example
Python :: how to get what type of file a file is in python 
Python :: python range in intervals of 10 
Python :: get key(s) for min value in dict python 
Python :: pickle save dict 
Python :: how to separate url from text in python 
Python :: install os conda 
Python :: python pretty print list of tuples 
Python :: python qt always on top 
Python :: plot multiindex columns pandas 
Python :: merge pandas datasets 
Python :: pandas check if any of the values in one column exist in another 
Python :: react-native-dropdown-picker 
Python :: list to csv python 
Python :: rename files with spaces in a folder python 
Python :: pyaduio linux 
Python :: matplotlib larger chart 
Python :: range function 
Python :: clean consol python 
Python :: python flask windows 
Python :: python contextmanager 
Python :: how to count specific element in a list python 
Python :: perform_update serializer django 
Python :: calculate pointbiseral correlation 
Python :: pandas dataframe to excel hyperlink length limit 
Python :: read pickle file 
Python :: install python windows powershell 
Python :: how to install os module in python 
Python :: how to run loops 3 times in python 
Python :: how to use css in php example 
Python :: append multiple values to 2d list python 
ADD CONTENT
Topic
Content
Source link
Name
5+5 =