5

I'm having difficulties to save a Base64 string through a serializer. I'm using django rest framework 2.4 and django 1.7. The model and serializer are as follow:

models.py

class TicketAttachmentAreas(models.Model):
    id = models.AutoField(primary_key=True)
    ticket = models.ForeignKey(Tickets)
    attachment_file = models.ForeignKey(AttachmentFiles, related_name='areas')
    x1 = models.IntegerField(blank=True, null=True)
    x2 = models.IntegerField(blank=True, null=True)
    y1 = models.IntegerField(blank=True, null=True)
    y2 = models.IntegerField(blank=True, null=True)
    paint_data = models.BinaryField(blank=True, null=True)

serializers.py

class TicketAttachmentAreasSerializer(serializers.HyperlinkedModelSerializer):
    ticket = serializers.PrimaryKeyRelatedField()
    attachment_file = serializers.PrimaryKeyRelatedField()

    class Meta:
        model = TicketAttachmentAreas
        fields = ('url', 'id', 'x1', 'y1', 'x2', 'y2', 'ticket', 'paint_data', 'attachment_file')

I'm simply trying to save data through the serializer with the following code:

serializer = TicketAttachmentAreasSerializer(data=data)
if serializer.is_valid():
    serializer.save()

Unfortunately, even though I have my base64 in data['paint_data'], serializer.data['paint_data'] is empty and thus not saved.

I'm guessing DRF modelSerializer does not recognize BinaryField and would need something like a serializers.BinaryField, or use a methodField to set it, but I'm very new to it and have currently no idea how to do this properly, so I'd really appreciate your help !

(currently I'm using the following work-around, but it's quite ugly:)

if serializer.is_valid():
    ticket_attachment_area = serializer.save()
    if 'paint_data' in data.keys():
        ticket_attachment_area.paint_data = base64.encodestring(data['paint_data'])
        ticket_attachment_area.save()
1

2 Answers 2

3

Look into writing a custom serializer field and using it in your serializer. You can specify how you want to convert between strings and bytes.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your help this part of the documentation has slipped out of me.
It would be nice to have a solution which works out of the box.
0

Django serializer is not fetching binary field value. You have to declare Charfield in serializer.

TicketAttachmentAreasSerializer(serializers.HyperlinkedModelSerializer):
    ticket = serializers.PrimaryKeyRelatedField()
    attachment_file = serializers.PrimaryKeyRelatedField()
    **paint_data = serializers.CharField()**

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.