Skip to content

Commit

Permalink
Add support for MultiSelectFields being listed in Admin.list_display
Browse files Browse the repository at this point in the history
  • Loading branch information
blag committed Feb 21, 2017
1 parent 123d22b commit 01dcad2
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
2 changes: 1 addition & 1 deletion example/app/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@


class BookAdmin(admin.ModelAdmin):
pass
list_display = ('title', 'categories', 'tags', 'published_in')


admin.site.register(Book, BookAdmin)
23 changes: 21 additions & 2 deletions multiselectfield/db/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,19 @@ def __init__(self, *args, **kwargs):
if self.max_choices is not None:
self.validators.append(MaxChoicesValidator(self.max_choices))

def _get_flatchoices(self):
l = super(MultiSelectField, self)._get_flatchoices()

class MSGFlatchoices(list):
# Used to trick django.contrib.admin.utils.display_for_field into
# not treating the list of values as a dictionary key (which errors
# out)
def __bool__(self):
return False
__nonzero__ = __bool__
return MSGFlatchoices(l)
flatchoices = property(_get_flatchoices)

def get_choices_default(self):
return self.get_choices(include_blank=False)

Expand Down Expand Up @@ -115,9 +128,15 @@ def get_db_prep_value(self, value, connection, prepared=False):
return value

def to_python(self, value):
choices = dict(self.flatchoices)

class MSGList(list):
def __str__(msgl):
return ', '.join([choices.get(int(i)) if i.isdigit() else choices.get(i) for i in msgl])

if value:
return value if isinstance(value, list) else value.split(',')
return []
return value if isinstance(value, list) else MSGList(value.split(','))
return MSGList([])

def from_db_value(self, value, expression, connection, context):
if value is None:
Expand Down

3 comments on commit 01dcad2

@lsaint
Copy link

@lsaint lsaint commented on 01dcad2 Mar 6, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

would you please upload this commit to pip?

@blag
Copy link
Collaborator Author

@blag blag commented on 01dcad2 Mar 7, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@lsaint I'm still waiting on somebody to make sure it works, but I'd like to. I think a happy medium would be for me to release it as an alpha version, since the solution I made isn't very Pythonic and I might want to change it. Would an alpha release work for you?

@lsaint
Copy link

@lsaint lsaint commented on 01dcad2 Mar 7, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep, that woule be nice. I just would like to fix the issuse in admin page right now.

Please sign in to comment.