Change Django ModelChoiceField to show users' full names rather than usernames

后端 未结 5 1096
不知归路
不知归路 2020-11-30 01:31

I have a form in my Django app (not in admin) that allows staff members to select a user from a dropdown.

forms.ModelChoiceField(queryset = User.objects.filt         


        
5条回答
  •  情深已故
    2020-11-30 01:54

    You can setup a custom ModelChoiceField that will return whatever label you'd like.

    Place something like this within a fields.py or wherever applicable.

    class UserModelChoiceField(ModelChoiceField):
        def label_from_instance(self, obj):
             return obj.get_full_name()
    

    Then when creating your form, simply use that field

     UserModelChoiceField(queryset=User.objects.filter(is_staff=False), required = False)
    

    More info can be found here

提交回复
热议问题