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

后端 未结 5 1104
不知归路
不知归路 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:56

    You can also make one custom ModelChoiceField to which you can pass a function. That way if you have different fields for which you want different attributes to be displayed, you can have only 1 class:

    class CustomModelChoiceField(forms.ModelChoiceField):
    name_function = staticmethod(lambda obj: obj)
    
    def __init__(self, name_function, *args, **kwargs):
        if not name_function is None: self.name_function = name_function
        super(CustomModelChoiceField, self).__init__(*args, **kwargs)
    
    def label_from_instance(self, obj):
         return self.name_function(obj);
    

    You can then call it as simply as this:

    form_field = CustomModelChoiceField(
        lambda obj: obj.get_full_name(),
        queryset=Whatever.objects.all(),
    )
    

    You can also pass None in case you're doing some dynamic stuff and it'll just basically default to a regular ModelChoiceField. I'm not too much of a python guy but this works for me.

提交回复
热议问题