Django Admin Attribute Decorator

Due to the extremely repetitive nature of setting method attributes for django’s admin, I’ve thought of coming up with a better way to manage those for years.

Finally implemented a decorator that does such a thing gracefully:

def admin_method_attributes(**outer_kwargs):
    """ Wrap an admin method with passed arguments as attributes and values.
    DRY way of extremely common admin manipulation such as setting short_description, allow_tags, etc.
    def method_decorator(func):
        for kw, arg in outer_kwargs.items():
            setattr(func, kw, arg)
        return func
    return method_decorator

# usage
class ModelAdmin(admin.ModelAdmin):
	@admin_method_attributes(short_description='Some Short Description', allow_tags=True)
	def my_admin_method(self, obj):
		return '''<em></em>'''

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s