Skip to content

Instantly share code, notes, and snippets.

@shamrin
Forked from shvechikov/preview_decorator.py
Last active August 29, 2015 14:21
Show Gist options
  • Save shamrin/12d72fb1ed11b899687d to your computer and use it in GitHub Desktop.
Save shamrin/12d72fb1ed11b899687d 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):
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('{}_preview'.format(field_name))
return method
def decorator(cls):
setattr(cls, '{}_preview'.format(fields[0]), make_method(fields[0]))
setattr(cls, '{}_preview'.format(fields[1]), make_method(fields[1]))
return cls
return decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment