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()