1

I have an order model with a followed_by field:

class order(models.Model):
   followed_by = models.ForeignKey(User, limit_choices_to={'groups__name': "Managers"})

I have several such models and forms for those models. By default the form displays a modelchoicefield listing users that are mangers. This is fine. But the display isn't nice: it gives the username, and I want first+last name. This would work nicely: Change Django ModelChoiceField to show users' full names rather than usernames

except that now in everyform I must declare the queryset to limit users to managers. Can I use the above method so that the custom modelchoicefield defaults to my filtered queryset. so then from a form I can just say:

followed_by = ManagerUserModelChoiceField()
Community
  • 1
  • 1
rsp
  • 811
  • 2
  • 12
  • 32

3 Answers3

0

Can you define the queryset on your ModelChoiceField child class?

class UserModelChoiceField(ModelChoiceField):
    # Query that returns set of valid choices
    queryset = User.objects.filter(group__name='Managers')
    def label_from_instance(self, obj):
        return obj.get_full_name()
Enrico
  • 10,377
  • 8
  • 44
  • 55
  • that was actually the first thing I tried but in my form when I declare the following: followed_by = UserModelChoiceField(), I get TypeError: __init__() takes at least 2 arguments (1 given). (See my answer below) – rsp Dec 09 '12 at 21:09
0

Try passing in the queryset as an argument to the ManagerUserModelChoiceField class.

followed_by = ModelChoiceField(queryset = User.objects.filter(groups__name="Managers")
Aidan Ewen
  • 13,049
  • 8
  • 63
  • 88
0

After my comment to @Enrico this thought occurred to me: I overwrote the "init" class on my custom field like so:

class UserModelChoiceField(forms.ModelChoiceField):
    def __init__(self, *args, **kwargs):
        super(UserModelChoiceField, self).__init__(queryset=User.objects.filter(groups__name="Managers"), *args, **kwargs)

I've seen stuff like this done in python before but I'm new to python so I'm not sure if this is a bad thing to do or if I should make this better somehow? I'd appreciate some feedback. That being said, it seems to be working correctly.

rsp
  • 811
  • 2
  • 12
  • 32