I am looking for a way to filter a multiple choice field in django forms such that one will see only a specific portion of the user database.
I have three models:
- a research results model (named
Forskningsresultater
); - a user model (the default
User
model); and - a custom-made M2M model between the first two models (named
PersonRes
). This custom-made M2M model has been imported using Django Import/Export.
Say that I have a model with 300 users and that one particular research result has 5 authors. In the form, I want to display checkboxes for only these 5 authors instead of all 300. The checkboxes are used to change the participant
field in the PersonRes
model (see the models.py
box below). Therefore, I want to:
- Subset so only authors related to a specific research result through the M2M model are shown.
- Even though a user unchecks an author as a participant (so that we have four checked authors and one unchecked), it should be able to go back to this form and still see all authors (here: all five authors) and make additional changes to all these authors if needed.
models.py
class Forskningsresultater(models.Model):
id = models.IntegerField(primary_key=True)
...
authors = models.ManyToManyField(settings.AUTH_USER_MODEL, through='PersonRes', blank=True,related_name='authors',verbose_name="Authors")
class PersonRes(models.Model):
id = models.IntegerField(primary_key=True)
user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,verbose_name="user")
forskningsresultater = models.ForeignKey(Forskningsresultater,on_delete=models.CASCADE, null=True,verbose_name="forskningsresultater")
participant = models.BooleanField(default=True)
forms.py
class ForskningsresultaterApproveForm(forms.ModelForm):
authors = forms.ModelMultipleChoiceField(required=False,queryset=User.objects,label="Participants",widget=forms.CheckboxSelectMultiple)
class Meta():
model = Forskningsresultater
fields = ('authors')
widgets = {
}
I suspect I should use .objects.filter(...)
in the form's queryset
, but I haven't found a functioning way to do it yet.