Skip to content

Instantly share code, notes, and snippets.

@gjbagrowski
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gjbagrowski/df74363a539c8f5f9f34 to your computer and use it in GitHub Desktop.
Save gjbagrowski/df74363a539c8f5f9f34 to your computer and use it in GitHub Desktop.
def model_attrs_unicode(instance, attrs=None):
"""Helper for creating simple instance string descriptions.
Accepts a list of string attributes names or functions that can be given by
specifying attrs or defining __UNICODE__ATTRS on the model.
If a get_{fieldname}_display method exists, it will be used instead of
simple getattr.
Attrs can contain function that accept model instance and return
(attrname, val) pairs, both must be unicode strings.
Keyword arguments:
instance -- source for fields
attrs -- attributes to generate unicode representation from
"""
if attrs is None:
display_attrs = getattr(instance, '__UNICODE__ATTRS', None)
else:
display_attrs = attrs
if display_attrs is None:
return None
def get_field_display(attrname):
display = getattr(instance, 'get_{}_display'.format(attrname), None)
if display is not None:
val = display
if callable(display):
val = display()
else:
if callable(attrname):
attrname, val = attrname(instance)
else:
val = getattr(instance, attrname)
return u'{}: {}'.format(attrname, val)
vals = [get_field_display(attrname) for attrname in display_attrs]
return u', '.join(vals)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment