I’m trying to filter the permissions on a form and display only the name.
I have come up with two possible solutions but they do not cover the requirements
The first shows the permissions correctly but shows a validation error saying that the selection is not valid.
class Permisos(ModelChoiceField):
def label_from_instance(self, obj):
return "{}".format(obj.name)
class UsuarioCreateForm(forms.ModelForm):
user_permissions = Permisos( queryset=Permission.objects.filter(content_type=ContentType.objects.get_for_model(RightsSupport)),
to_field_name='pk', widget=forms.SelectMultiple(), label='Permisos de usuario', required=False,
help_text="Permisos específicos para este usuario.", )
class Meta:
model = Usuario
The second one has no errors but shows application|model|permission. I just want the permission to show.
class UsuarioCreateForm(forms.ModelForm):
class Meta:
model = Usuario
fields = [
'user_permissions',
]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['user_permissions'].queryset = Permission.objects.filter(content_type=ContentType.objects.get_for_model(RightsSupport))
Individually. The two options show identical html, except for the permission name and only the first option gives a validation error, the second works correctly except for the compound name part.
I just noticed that you don’t have the fields attribute in the Meta class in your first form. (Is it there and you just don’t show it? What else is in that form?)
I found the error after running step by step and following the validation path.
I was using the wrong inheritance, ModelChoiceField instead of ModelMultipleChoiceField.
class Permisos(ModelMultipleChoiceField):
def label_from_instance(self, obj):
return "{}".format(obj.name)