Skip to content

Instantly share code, notes, and snippets.

@shvechikov
Last active August 29, 2015 14:21
Show Gist options
  • Save shvechikov/d329c0564c1a9ec17c53 to your computer and use it in GitHub Desktop.
Save shvechikov/d329c0564c1a9ec17c53 to your computer and use it in GitHub Desktop.
def add_preview_for(*fields):
"""
This is a decorator for model classes that adds preview methods.
So instead of manually adding preview methods:
>>> class Student(models.Model):
... photo = models.ImageField()
... icon = models.ImageField()
...
... def preview_photo(self):
... if not self.photo:
... return '(no photo)'
... return u'<img src="{}" />'.format(self.photo.url)
...
... def preview_icon(self):
... if not self.icon:
... return '(no icon)'
... return u'<img src="{}" />'.format(self.icon.url)
You just can use this decorator with the same result:
>>> @add_preview_for('photo', 'icon')
... class Student(models.Model):
... photo = models.ImageField()
... icon = models.ImageField()
"""
html = u'<img src="{}" style="max-width: 100px; max-height: 100px" />'
def make_method(field_name):
method_name = '{}_preview'.format(field_name)
def method(self):
field = getattr(self, field_name)
if not field:
return '(no {})'.format(field_name)
return html.format(field.url)
method.short_description = '{} preview'.format(field_name.capitalize())
method.allow_tags = True
method.__name__ = str(method_name)
return method_name, method
def decorator(cls):
for field_name in fields:
method_name, method = make_method(field_name)
setattr(cls, method_name, method)
return cls
return decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment