Login

Base64Field: base64 encoding field for storing binary data in Django TextFields

Author:
bikeshedder
Posted:
August 5, 2009
Language:
Python
Version:
1.1
Score:
5 (after 5 ratings)

This Base64Field class can be used as an alternative to a BlobField, which is not supported by Django out of the box.

The base64 encoded data can be accessed by appending _base64 to the field name. This is especially handy when using this field for sending eMails with attachment which need to be base64 encoded anyways.

Example use:

class Foo(models.Model):
    data = Base64Field()

foo = Foo()
foo.data = 'Hello world!'
print foo.data # will 'Hello world!'
print foo.data_base64 # will print 'SGVsbG8gd29ybGQh\n'
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import base64

from django.db import models


class Base64Field(models.TextField):

    def contribute_to_class(self, cls, name):
        if self.db_column is None:
            self.db_column = name
        self.field_name = name + '_base64'
        super(Base64Field, self).contribute_to_class(cls, self.field_name)
        setattr(cls, name, property(self.get_data, self.set_data))

    def get_data(self, obj):
        return base64.decodestring(getattr(obj, self.field_name))

    def set_data(self, obj, data):
        setattr(obj, self.field_name, base64.encodestring(data))

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

kylec (on December 16, 2010):

To store values larger than 48k, add a db_type method that returns 'longtext'.

#

seafangs (on September 3, 2012):

Great snippet, thank you. Very useful in my current situation (which is: don't don't don't want to store images in a Blob, but have been more or less commanded to, as a 'holdover' or whatever).

#

seafangs (on September 3, 2012):

and great tip kylec, thank you too

#

cristianmoreno2017 (on February 16, 2018):

hello, do you have another example of how to encode and decode base64 with django?

#

Please login first before commenting.