是否可以在Django Select2表单中过滤queryset ?
我有一个向用户发送直接消息的表单,我希望能够过滤用户。
s2forms。ModelSelect2Widget如我所见,选择User model
的所有实例现在我需要为User模型实现一个标志(allow_direct_messages),如果用户允许发送直接消息,那么我需要相应地过滤它们。
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",
]
也许有人知道如何在ModelSelect2Widget中制作自定义查询集形式?
Thanks in advance
我找到解决办法了希望对大家有所帮助
不要害怕设置查询集属性:
class UsersWidget(s2forms.ModelSelect2Widget):
*queryset = User.objects.exclude(profile__allow_direct_messages=False)*
search_fields = [
"name__icontains",
"email__icontains",
]
这应该可以工作!