Code

Opened 7 years ago

Closed 6 years ago

#4620 closed (fixed)

Custom labels for choices in ModelChoiceField

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

Description

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@…> 7 years ago.
Adds a function to the query set iterator and model*choicefield
4620_all.diff (4.8 KB) - added by PhiR 6 years ago.
patch with fix + doc + tests

Download all attachments as: .zip

Change History (17)

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

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

comment:1 Changed 7 years ago by SmileyChris

  • Needs documentation set
  • Needs tests set
  • Patch needs improvement unset
  • Triage Stage changed from Unreviewed to Design 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 7 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 7 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 6 years ago by jacob

  • Resolution set to wontfix
  • Status changed from new to closed

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

comment:5 Changed 6 years ago by SmileyChris

  • Resolution wontfix deleted
  • Status changed from closed to reopened

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 follow-up: Changed 6 years ago by jacob

  • Resolution set to wontfix
  • Status changed from reopened to closed

Yes, we're sure this is wontfix.

comment:7 Changed 6 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 6 years ago by moya

  • Resolution wontfix deleted
  • Status changed from closed to reopened

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 6 years ago by mtredinnick

  • Resolution set to wontfix
  • Status changed from reopened to closed

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

comment:10 Changed 6 years ago by jacob

  • Patch needs improvement set
  • Resolution wontfix deleted
  • Status changed from closed to reopened
  • Triage Stage changed from Design decision needed to Accepted

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 6 years ago by Alex

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

Changed 6 years ago by PhiR

patch with fix + doc + tests

comment:12 Changed 6 years ago by jacob

  • Owner changed from nobody to jacob
  • Status changed from reopened to new
  • Triage Stage changed from Accepted to Ready for checkin

comment:13 Changed 6 years ago by jacob

  • Resolution set to fixed
  • Status changed from new to closed

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

comment:14 Changed 6 years ago by PhiR

  • Needs documentation unset
  • Resolution fixed deleted
  • Status changed from closed to reopened
  • Triage Stage changed from Ready for checkin to Accepted
  • Version changed from 0.96 to SVN

comment:15 Changed 6 years ago by PhiR

  • Needs tests unset
  • Patch needs improvement unset
  • Resolution set to fixed
  • Status changed from reopened to closed

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

Add Comment

Modify Ticket

Change Properties
<Author field>
Action
as closed
as The resolution will be set. Next status will be 'closed'
The resolution will be deleted. Next status will be 'new'
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.