Last active
December 30, 2016 22:01
-
-
Save ebertti/b12a954ce0feaded9d58274e1352af1f to your computer and use it in GitHub Desktop.
Smart label using, django-choices, django-suit (bootstrap2) and django-admin-easy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Kind(DjangoChoices): | |
Default = C(value='default') | |
Success = C(value='success') | |
Warning = C(value='warning') | |
Important = C(value='important') | |
Info = C(value='info') | |
Inverse = C(value='inverse') | |
class CK(ChoiceItem): | |
def __init__(self, value=None, label=None, order=None, kind=None): | |
super().__init__(value, label, order) | |
self.kind = kind or Kind.Default | |
class StatusBase(DjangoChoices): | |
Ativo = CK(kind=Kind.Success) | |
Inativo = CK(kind=Kind.Info) | |
import easy | |
from django.utils.module_loading import import_string | |
from easy import helper | |
class LabelAdminField(easy.SimpleAdminField): | |
def __init__(self, attr, django_choice): | |
if isinstance(django_choice, str): | |
self.choice = import_string(django_choice) | |
else: | |
self.choice = django_choice | |
self.montar_tipos() | |
super().__init__(attr, allow_tags=True) | |
def montar_tipos(self): | |
self.tipos = {} | |
for chave, choice in self.choice._fields.items(): | |
if hasattr(choice, 'kind'): | |
self.tipos[getattr(self.choice, chave)] = choice.kind | |
def render(self, obj): | |
valor = super().render(obj) | |
display = helper.call_or_get(obj, 'get_' + self.attr + '_display', self.default) | |
return '<span class="label label-%s">%s</span>' % (self.tipos.get(valor, ''), display) | |
class MyAdmin(admin.ModelAdmin): | |
my_easy_field = LabelAdminField('field_name', 'path.to.django_choice') | |
my_easy_field2 = LabelAdminField('field_name', StatusBase) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment