Opened 14 years ago

Closed 14 years ago

#4620 closed (fixed)

Custom labels for choices in ModelChoiceField

Reported by: Bill Fenner <fenner@…> Owned by: Jacob
Component: Forms Version: dev
Severity: Keywords:
Cc: Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


I wanted to display a different value than the str() for a certain ModelChoiceField I was building. I added a func arg to both ModelChoiceField and QuerySetIterator to allow passing a function to change the behavior of the labels - e.g.,

    field = forms.ModelChoiceField(IESGLogin.objects.all(), func = lambda ad: "%s, %s" % (ad.last_name, ad.first_name))

to get "Fenner, Bill" instead of the default str representation of "Bill Fenner".

ModelMultipleChoiceField is similarly modified, and you can of course call more complex functions

    field2 = ModelMultipleChoiceField(IDState.objects.all(), func=lambda f:truncate_words(str(f),2))

Attachments (2)

queryset-lambda.diff (2.9 KB) - added by Bill Fenner <fenner@…> 14 years ago.
Adds a function to the query set iterator and model*choicefield
4620_all.diff (4.8 KB) - added by Philippe Raoult 14 years ago.
patch with fix + doc + tests

Download all attachments as: .zip

Change History (17)

Changed 14 years ago by Bill Fenner <fenner@…>

Attachment: queryset-lambda.diff added

Adds a function to the query set iterator and model*choicefield

comment:1 Changed 14 years ago by Chris Beaven

Needs documentation: set
Needs tests: set
Triage Stage: UnreviewedDesign decision needed

Looks good! I think perhaps func should a bit more definitive, something like label_func.

I'll leave as design decision for the big cheeses to review.

comment:2 Changed 14 years ago by david@…

Bill submitted this ticket after talking with me on IRC. It's a nice addition, preventing my SELECT boxes from spanning 2 screen widths.

comment:3 Changed 14 years ago by bsdlogical

This would be an excellent feature to have. I was looking for a feature exactly like this until I found this patch.

comment:4 Changed 14 years ago by Jacob

Resolution: wontfix
Status: newclosed

The right way to do this is to subclass ModelChoiceField (i.e. write a PersonChoiceField) and add the correct behavior there.

comment:5 Changed 14 years ago by Chris Beaven

Resolution: wontfix
Status: closedreopened

It's a lot of hoops to jump through to do that however:

  1. Subclass QuerySetIterator
  1. On your iterator subclass, override (and duplicate most of) the __iter__ method to just yield something other than smart_unicode(obj)
  1. Subclass ModelChoiceField or ModelMultipleChoiceField
  1. On your field subclass, create (mostly duplicate) _get_choices and _set_choices methods and set choices = property(_get_choices, _set_choices) so you can use your subclassed iterator

I've had this request again recently on IRC - are you sure it's wontfix? (even if it is in a different way to the current patch)

comment:6 Changed 14 years ago by Jacob

Resolution: wontfix
Status: reopenedclosed

Yes, we're sure this is wontfix.

comment:7 Changed 14 years ago by sjulean

There are two possible solutions to this issue that don't involve passing a display function to the ModelChoiceField:

Solution #1:

  1. Write a new method like __unicode__ that returns whatever you need.
  2. Subclass from QuerySet, override get to replace the __unicode__ method of the returned objects. This subclass could be returned by a metaclass which receives the replacement __unicode__ function (or any other override, for that matter) in kwargs.
  3. Subclass from Manager, override get_query_set to return the QuerySet subclass defined above. This subclass could also be returned by a metaclass which uses the above metaclass to create QuerySet subclasses with specific parameters.
  4. Make it possible to pass the custom manager to ModelChoiceField. Currently get_choices always uses _default_manager.

Solution #2:

  1. Write a new method like __unicode__ that returns whatever you need.
  2. Write a method for your model that clones the model, changes the __unicode__ method to the new one, and returns the modified model instance. For the sake of this example let's call this method shorter_display. (This can work for any overrides.)
  3. Make it possible to pass a custom choice list to ModelChoiceField. The elements of that list should be instances of the given model class. This parameter (let's call it choices) is mutually exclusive with limit_choices_to.
  4. field = ModelChoiceField(Model, choices=[object.shorter_display() for object in Model.objects.all()])

Both of the proposed solutions are considerably more flexible than the label_func proposition. As overriding the label is a common scenario, the metaclasses in Solution #1 could actually be included in Django and not left to the users to create.

For the moment you can pass neither choices nor manager (and certainly not label_func above) - in this situation I'm using a subclassed widget that specifies the choices on __init__ and render. And I feel that this is a very ugly solution.

comment:8 in reply to:  6 Changed 14 years ago by moya

Resolution: wontfix
Status: closedreopened

Replying to jacob:

Yes, we're sure this is wontfix.

Could you please give a short rationale on this given that having custom labels is not trivial as you did think before. The solution, as SmileyChris explained, involves some code duplication (maybe more code duplicated than the actual bits used for getting the custom label itself)

I have a class Foo that have a user = ForeignKey(User) and would like to choose users for Foo instances by their full name instead of by their username. User here is the standard class from django.contrib.auth and so it's outside my control.

The needing of displaying full names instead of usernames in a ModelChoiceField for django.contrib.auth.models.User doesn't seem so uncommon to me.

comment:9 Changed 14 years ago by Malcolm Tredinnick

Resolution: wontfix
Status: reopenedclosed

Please bring such questions up on the django-developers list, rather than reopening the ticket (as documented in contributing.txt).

comment:10 Changed 14 years ago by Jacob

Patch needs improvement: set
Resolution: wontfix
Status: closedreopened
Triage Stage: Design decision neededAccepted

Reopening after discussion on django-dev. I'm none to happy with the specific approach presented in this patch, but it *is* simply too hard to get custom labels out of a ModelChoiceField.

comment:11 Changed 14 years ago by Alex Gaynor

In the current patch, instead of having the default function be lambda obj: str(obj), why not just give it smart_unicode?

Changed 14 years ago by Philippe Raoult

Attachment: 4620_all.diff added

patch with fix + doc + tests

comment:12 Changed 14 years ago by Jacob

Owner: changed from nobody to Jacob
Status: reopenednew
Triage Stage: AcceptedReady for checkin

comment:13 Changed 14 years ago by Jacob

Resolution: fixed
Status: newclosed

(In [7326]) Fixed #4620: you can now easily add custom labels to ModelChoiceFields via subclassing. Thanks, PhiR.

comment:14 Changed 14 years ago by Philippe Raoult

Needs documentation: unset
Resolution: fixed
Status: closedreopened
Triage Stage: Ready for checkinAccepted
Version: 0.96SVN

comment:15 Changed 14 years ago by Philippe Raoult

Needs tests: unset
Patch needs improvement: unset
Resolution: fixed
Status: reopenedclosed

was not used correctly, user reports it works as expected when used as documented.

Note: See TracTickets for help on using tickets.
Back to Top