Search code examples
pythonjsondjangodjango-modelsdjango-jsonfield

InterfaceError for a custom JSONField for Django


I am trying to build a custom JSON Field for Django projects that support MySQL. This is my models:

from __future__ import unicode_literals
from django.db import models
from django.db import models
from django.core.serializers.json import DjangoJSONEncoder
import json

name1 = 'name1'
name2 = 'name2'

class JSONField(models.TextField):
    """JSONField is a generic textfield that neatly serializes/unserializes
    JSON objects seamlessly"""

    # Used so to_python() is called
    __metaclass__ = models.SubfieldBase

    def to_python(self, value):
        """Convert our string value to JSON after we load it from the DB"""

        if value == "":
            return None

        try:
            if isinstance(value, basestring):
                return json.loads(value)
        except ValueError:
            pass

        return value

    def get_db_prep_save(self, value, connection):
        """Convert our JSON object to a string before we save"""

        if value == "":
            return None

        if isinstance(value, dict):
            value = json.dumps(value, cls=DjangoJSONEncoder)

        return super(JSONField, self).get_db_prep_save(value, connection)

# Articles / Content
class Content(models.Model):
    title = models.CharField(max_length=255)
    body = models.TextField()
    data = JSONField(blank=True, null=True)

    def __unicode__(self):
        return self.title

    def save(self, *args, **kwargs):
        self.data = {
            name1 : {
                "image_url" : 'https://photosite.com/image1.jpg',
                "views" : 0
            },
            name2 : {
                 "image_url" : 'https://photosite.com/image2.jpg',
                 "views" : 0
            }
        }
        super(Content, self).save(*args, **kwargs)

Please notice the custom save method for the Content model. When I try to save a new Content object, I get this error:

InterfaceError at /admin/myapp/content/add/

Error binding parameter 2 - probably unsupported type.

What exactly am I doing wrong? What does the error even mean. I mean it says 'probably', as if its not even sure if there is an error. Any help?

If you want the full traceback, you can find it here: http://pastebin.com/B15hZpbu


Solution

  • this code will produce an undefined variable error before you call your user method.

    data = {
            name1 : {
                "image_url" : 'https://photosite.com/image1.jpg',
                "views" : 0
            },
            name2 : {
                 "image_url" : 'https://photosite.com/image2.jpg',
                 "views" : 0
            }
        }
    

    name1 and name2 are clearly not defined in your code.