jamesturk/django-markupfield

'unicode' object has no attribute 'raw' with Django REST-Framework

Closed this issue · 2 comments

I'm trying to have the Django REST Framework serialize a MarkupField, however there appears to be an error during serialization when calling the value_to_string method. On line 156 of fields.py

def value_to_string(self, obj):
    value = self._get_val_from_obj(obj)
    return value.raw

When obj is None, the _get_val_from_obj method appears to return u'', which does not have a raw properterty to access.

Proposed fix:

def value_to_string(self, obj):
    if obj is None: return u''
    value = self._get_val_from_obj(obj)
    return value.raw

any chance you can submit a pull request with a test for this?

Yep, that is no problem. I just want to run all the tests and make sure everything is 100%. It doesn't seem like this change will cause too much issue, but then again- you never know.

Another possibility exists. The source of the issue is in the fields module, line 763, here is the method:

def _get_val_from_obj(self, obj):
    if obj is not None:
        return getattr(obj, self.attname)
    else:
        return self.get_default()

This is why when obj is None, the default returns u'' - we could override get_default to return self, which would then ensure that the value would have the raw property.

Another option:

def value_to_string(self, obj):
    value = self._get_val_from_obj(obj)
    if hasattr(value, 'raw'):
        return value.raw
    return value

After my tests, I'm favoring the last method, but I welcome your opinion. When I hear back from you, I'll send back the pull request.