Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable on/off icon for boolean field in Django

Sometimes it is not desirable to show 'on/off' icon for a boolean field.

Example:

  • error field shows a happy green 'ok' icon when there's an error or
  • blocked=True displayed as a green 'ok' while blocked=False as a 'no entry' sign.

In such cases it'd be better to keep the original True/False behaviour.

Is there a more elegant way than creating a special method returning for example self.error and adding short_description, ordering, etc. to it?

like image 466
Antony Hatchkins Avatar asked Dec 21 '12 13:12

Antony Hatchkins


2 Answers

There is no dirtiness in using this code admin.py:

from mysite.models import Test
from django.contrib import admin

class TestAdmin(admin.ModelAdmin):
    list_display = ('is_blocked_col',)

    def is_blocked_col(self, obj):
        return not obj.is_blocked # invert the boolean value
    is_blocked_col.boolean = True
    is_blocked_col.admin_order_field = 'is_blocked'
    is_blocked_col.short_description  = 'Is Blocked'

admin.site.register(Test, TestAdmin)

If you use this method it will still show the on/off icon. If is_blocked=True then return not obj.is_blocked is going to return False which shown as red icon as desired by you.

EDIT

If you want to use the words True/False instead of the red/green icons you can set

is_blocked_col.boolean = False

in the above code.

like image 107
Aamir Rind Avatar answered Nov 08 '22 22:11

Aamir Rind


I examined the corresponding django code and unfortunately this behaviour is hard-coded so the only solution is the one mentioned in the question:

is_blocked = BooleanField(default=False)

def is_blocked_col(self):
    return self.is_blocked
is_blocked_col.short_description = \
is_blocked_col.admin_order_field = 'is_blocked'

Which is much less readable than something like

is_blocked = BooleanField(default=False)
is_blocked.boolean = False

(which doesn't work)

or than forcing admin widget to force_unicode or something (which I am not sure how to implement)

like image 39
Antony Hatchkins Avatar answered Nov 08 '22 21:11

Antony Hatchkins