djangodjango-modelsdjango-viewsdjango-formsdjango-select2

Filter queryset in django select2 widget


Is it possible to filter queryset in Django Select2 forms?

I got a form that sends a direct message to the user and I want to have the possibility to filter users.

s2forms.ModelSelect2Widget, as I see, selects all instances of User model

Now I need t to implement a flag to the User model (allow_direct_messages), and if the user allows sending direct messages, so I need to filter them accordingly.

class DirectMessageCreateForm(forms.ModelForm):
class Meta:
    model = DirectMessage
    fields = ("author", "recipient", "content")
    labels = {
        "author": "",
    }
    widgets = {
        "recipient": UsersWidget,
        "content": forms.Textarea(attrs={
            'class': 'block p-3 w-full text-md bg-gray-50 rounded-lg border border-gray-300 focus:ring-blue-500'
                     ' focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 '
                     'dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500',
            'placeholder': "Type your message here..."
        }),
        "author": forms.TextInput,
    }



class UsersWidget(s2forms.ModelSelect2Widget):
search_fields = [
    "name__icontains",
    "email__icontains",
]

Maybe someone knows how to make a custom queryset inside ModelSelect2Widget form?

Thanks in advance


Solution

  • I found solution Hope it will help somebody

    Don`t be afraid to set a queryset attribute inside your class:

    class UsersWidget(s2forms.ModelSelect2Widget):
    *queryset = User.objects.exclude(profile__allow_direct_messages=False)*
    search_fields = [
        "name__icontains",
        "email__icontains",
    ]
    

    This should work!