Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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
... return '(no photo)'
... return u'<img src="{}" />'.format(
... 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