[Answer]-How to override __unicode__ on Django Auth.Group instance in form?

1👍

ModelChoiceField and ModelMultipleChoiceField allow you to override labels in select box.

First subclass field class and override label_from_instance method.

class GroupMultipleChoiceField(forms.ModelMultipleChoiceField):

    def label_from_instance(self, obj):
        return prettify_group(obj)

Now use this field instead of standard ModelMultipleChoiceField in your form:

class InternalActorForm(forms.ModelForm):

    groups = GroupMultipleChoiceField(queryset=Group.objects.all())

    def __init__(self, *args, **kwargs):
        ...

This is a documented Django feature.

0👍

Another solution would be to update the choices list from this field with the filtered values:

def __init__(self, *args, **kwargs):
    super(InternalActorForm, self).__init__(*args, **kwargs)
    self.fields['groups'].choices = [(gid, filters.prettify_group(name)) for gid, name in self.fields['groups'].choices]

But I guess it’s a hackish way to do what @catavaran suggested.

Leave a comment