Home > OS >  REST Django - How to Modify a Serialized File Before it is Put Into Model
REST Django - How to Modify a Serialized File Before it is Put Into Model

Time:02-20

I am hoping that I can find a way to resize an uploaded image file before it is put into the database. I am new to Django with REST, so I am not sure how this would be done. It seems that whatever is serialized is just kind of automatically railroaded right into the model. Which I suppose is the point (it's certainly an easy thing to setup).

To clarify, I already have a function tested and working that resizes the image for me. That can be modified as needed and is no problem for me. The issue really is about sort of "intercepting" the image, making my changes, and then putting it into the model. Could someone help me out with some ideas of tactics to get that done? Thanks.

The Model:

class Media(models.Model):
    objects = None
    username = models.ForeignKey(User, to_field='username',
                                 related_name="Upload_username",
                                 on_delete=models.DO_NOTHING)
    date = models.DateTimeField(auto_now_add=True)
    media = models.FileField(upload_to='albumMedia', null=True)
    file_type = models.CharField(max_length=12)
    MEDIA_TYPES = (
        ('I', "Image"),
        ('V', "Video")
    )
    media_type = models.CharField(max_length=1, choices=MEDIA_TYPES, default='I')

    user_access = models.CharField(max_length=1, choices=ACCESSIBILITY, default='P')

    class Meta:
        verbose_name = "MediaManager"

The View with post method:

class MediaView(APIView):
    queryset = Media.objects.all()
    parser_classes = (MultiPartParser, FormParser)
    permission_classes = [permissions.IsAuthenticated, ]
    serializer_class = MediaSerializer

    def post(self, request, *args, **kwargs):
        user = self.request.user
        print(user.username)
        request.data.update({"username": user.username})
        media_serializer = MediaSerializer(data=request.data)
        # media_serializer.update('username', user.username)
        if media_serializer .is_valid():
            media_serializer.save()
            return Response(media_serializer.data, status=status.HTTP_201_CREATED)
        else:
            print('error', media_serializer.errors)
            return Response(media_serializer.errors,status=status.HTTP_400_BAD_REQUEST)

The Serializer:

class MediaSerializer(serializers.ModelSerializer):
    class Meta:
        model = Media
        fields = '__all__'
    def to_representation(self, instance):
        data = super(MediaSerializer, self).to_representation(instance)
        return data

CodePudding user response:

You can use validate method to validate and/or change the values from data dictionary.

class MediaSerializer(serializers.ModelSerializer):
    ...
    def validate(self, data):
        value_from_form = data['value_from_form']
        
        value_from_form = 'Something else'

        data['value_from_form'] = value_from_form 

        return data
  • Related