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 :: removing a channel from aconda 
Python :: python change comma to dot 
Python :: date parser python pandas 
Python :: opencv python shrink image 
Python :: char list 
Python :: gpu training tensorflow 
Python :: How to make an simple python client 
Python :: segregate list in even and odd numbers python 
Python :: how to print dataframe in python without index 
Python :: python how to get every name in folder 
Python :: simple thresholding with OpenCV 
Python :: python print without space 
Python :: plt change legend coordinates 
Python :: django session expire time 
Python :: tkinter draw squaer 
Python :: code for making an exe file for python 
Python :: make csv lowercase python 
Python :: pd max rows set option 
Python :: matplotlib boxplot remove outliers 
Python :: How to find the three largest values of an array efficiently, in Python? 
Python :: django setup allowed hosts 
Python :: download image python 
Python :: with python how to check alomost similar words 
Python :: ModuleNotFoundError: No module named ‘click’ 
Python :: pandas unnamed zero 
Python :: django querset group by sum 
Python :: max of a dict 
Python :: split list in 3 part 
Python :: ses mail name 
Python :: amazon cli on commadline 
ADD CONTENT
Topic
Content
Source link
Name
4+6 =