1

forms.py

class PermissionForm(forms.Form):
    def __init__(self, *args, **kwargs):
        self.rolesChoices = kwargs.pop('rolesChoices')
        super(PermissionForm, self).__init__(*args, **kwargs)
        print(self.rolesChoices)
        self.fields['roles'].queryset = self.rolesChoices
        print(self.fields['roles'].queryset)
    roles = forms.ModelChoiceField(
        queryset=None, widget=forms.CheckboxSelectMultiple, empty_label=None)

views.py

def privileges(request):
    rolesChoices = Permission.objects.filter(
        content_type=ContentType.objects.get_for_model(Group))
    for role in rolesChoices:
        role.name = role.name.replace("group", "role")
    form = PermissionForm(rolesChoices=rolesChoices)
    return render(request, 'crm/privileges.html', {'form': form})

I am passing group objects to my form when I am initializing it in views.But I am done a small change, I replaced group with role.So the problem is role get changed with group automatically.I don't know why it's happenging.

For example self.roleChoices contains Can add role When I assign self.roleChoices to self.fields['roles'].queryset it changes to Can add group

enter image description here

1 Answer 1

1

The problem is that, when you do the following:

    for role in rolesChoices:
        role.name = role.name.replace("group", "role")

You execute the queryset, which creates a list of results cached in the queryset.

Then, when you do:

self.fields['roles'].queryset = self.rolesChoices

You actually call self.fields['roles']._set_queryset(self.rolesChoices) as queryset is a property that ensures calling .all() on your queryset.

If you need to operate such changes on the results before showing it in your form, I would recommend to use a ChoiceField instead of a ModelChoiceField. Thus you can set the choices attribute as you wish.

However, in this case you might be able to bypass the property using _queryset: self.fields['roles']._queryset = self.rolesChoices. Although you might face other issues later if the queryset is called again with .all() or .filter().

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.