Code

Opened 6 years ago

Closed 6 years ago

#6839 closed (invalid)

using label_from_instance on ModelChoiceField requires resetting queryset first

Reported by: Koen Biermans <koen.biermans@…> Owned by: nobody
Component: Forms Version: master
Severity: Keywords: ModelChoiceField
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: UI/UX:

Description

Overriding the new label_from_instance on ModelChoiceField (introduced in r7326) requires also resetting the queryset on the field for the new label_from_instance function to be used.
A short example:

class Aform(forms.Form):
    user = forms.ModelChoiceField(queryset=User.objects.all())

    def __init__(self, *args, **kwargs):
        super(Aform, self).__init__(*args, **kwargs)
        # without the next line label_from_instance does NOT work
        self.fields['user'].queryset = User.objects.all()
        self.fields['user'].label_from_instance = lambda obj: "%s %s" % (obj.last_name, obj.first_name)

If I do not redefine the queryset in init, it does not work. If I do, it does.

Attachments (0)

Change History (1)

comment:1 Changed 6 years ago by ubernostrum

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Resolution set to invalid
  • Status changed from new to closed

The idea here is to subclass ModelChoiceField and override label_from_instance. Which, coincidentally, is precisely what the docstring on label_from_instance says you should do.

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.