Reputation: 13
I have a form to ask for a title and a list of users. My problem is that I want to display all the users in the database but exclude the current authenticated user. I have tried several options but they were not right. Could you help me? Thank you:
from django import forms
class FormCal(forms.Form):
titulo = forms.CharField(max_length=100)
usuarios = forms.ModelMultipleChoiceField(queryset=User.objects.all(), widget=forms.CheckboxSelectMultiple(), required=False)
Upvotes: 1
Views: 138
Reputation: 4818
You can access the request object in __init__
of form class. You can dynamically adjust the queryset there.
class FormCal(forms.Form):
titulo = forms.CharField(max_length=100)
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super(FormCal, self).__init__(*args, **kwargs)
# exclude logged in user from queryset
usuarios_queryset = User.objects.all().exclude(username=self.request.user.username)
# add field to form
self.fields['usuarios'] = forms.ModelMultipleChoiceField(
queryset=usuarios_queryset,
widget=forms.CheckboxSelectMultiple(),
required=False)
Upvotes: 1