When I create custom permissions, After saving it automatically deleting the saved permissions in Django
In the Django admin class for the group creation page, I added additional fields. Based on these fields, I need to filter and set the permissions for the group. However, the issue arises in the save method. Although it saves the permissions, I noticed during debugging that the save_m2m() method in the superclass deletes all the assigned permissions
class CustomGroupForm(forms.ModelForm):
env_name = forms.CharField(max_length=100, required=False)
schema_name = forms.CharField(max_length=100, required=False)
class Meta:
model = Group
fields = ['name', 'permissions', 'env_name', 'schema_name']
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['permissions'].queryset = Permission.objects.none()
def save(self, commit=True):
group = super().save(commit=False)
# Use the name field as the prefix to filter permissions
name = self.cleaned_data.get('name', '')
prefix = name
logger.info(f'Prefix 1: {prefix}')
# Filter permissions using the prefix
filtered_permissions = Permission.objects.filter(
content_type__app_label__startswith=prefix
)
# Save the group first to ensure it has an ID
group.save()
# Set the filtered permissions
group.permissions.set(filtered_permissions)
if commit:
group.save()
return group
I expected the custom logic in the save method to correctly save the filtered permissions to the group without being overwritten. Specifically, I wanted the dynamically filtered permissions to persist after saving, without the save_m2m() method clearing them.