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.
- [Answer]-Django saving form field in generic or functional view
- [Answer]-Tags doesn't created with django-taggit
- [Answer]-Redirecting from one form to another form in Django
- [Answer]-Django multiple Forms in a single Form instance,validation error
Source:stackexchange.com