M.Izzat
M.Izzat

Reputation: 1166

Django CheckboxSelectMultiple widget : render only selected data by default

Greeting, I have a manytomany field call user in my model_A model, in my form, how can I display only the list of selected data associated to the model_A by default instead of listing entire entries from the User model in my html page? my intention is to create a setting page where I can remove the user associated to a project

below is my code :

model.py :

class model_A(models.Model):
    user = models.ManyToManyField(User, blank=True)

form.py :

class EditForm(forms.ModelForm):
    prefix = 'edit_form'
    class Meta:
        model = model_A
        fields = '__all__'
        widgets = {'user':forms.CheckboxSelectMultiple}

html :

<div class="field">
    {{form.user}}
</div>   

Any help is much appreciated thanks

Upvotes: 0

Views: 60

Answers (1)

Satendra
Satendra

Reputation: 6865

Change user queryset inside __init__ method of EditForm class.

class EditForm(forms.ModelForm):
    prefix = 'edit_form'
    class Meta:
        model = model_A
        fields = '__all__'
        widgets = {'user':forms.CheckboxSelectMultiple}

    def __init__(self, **kwargs):
        self.event = kwargs.pop('event')
        super().__init__(**kwargs)
        # replace dots with your conditions in filter
        self.fields['user'].queryset = self.user.filter(...) 

UPDATE

List users that are associated with Model_A

self.fields['user'].queryset = self.user.all()

Upvotes: 1

Related Questions