我有一个Django表单,其中包含一个TypedMultipleChoiceField,其中包含一组用户。我从auth User模型中获得了用户,但是我想从选择中删除当前登录的用户。我一直在尝试通过将请求数据引入表单的init方法,然后从选择列表中删除登录用户来执行此操作,但是由于某种原因,表单仍会在选择列表中呈现登录用户。代码如下:
Views.py
class IndexView(LoginRequiredMixin, generic.ListView, generic.edit.FormMixin):
def get_form_kwargs(self):
kwargs = super(IndexView, self).get_form_kwargs()
kwargs.update({'user': self.request.user})
return kwargs
def get_queryset(self):
return Project.objects.filter(owner=self.request.user.id).order_by('begin_date')
form_class = CreateProject
context_object_name = 'project_list'
template_name = 'projects/project_index.html'
表格
class CreateProject(forms.Form):
contributor_id = forms.TypedMultipleChoiceField(choices=list(User.objects.values_list('id','username')),
required=False, empty_value=[])
def __init__(self, *args, **kwargs):
self.user = kwargs.pop("user")
super(CreateProject, self).__init__(*args, **kwargs)
choices = self.fields['contributor_id'].choices
del choices[choices.index((self.user.id, self.user.username))]
当我将pdb.set_trace()放入init方法中并在执行删除操作后检查表单字段的状态时,一切看起来都正确。我究竟做错了什么?
作为参考,我在视图和窗体的init中将this用于get_form_kwargs。
最佳答案
解决方案是将TypedMultipleChoiceField更改为ModelMultipleChoiceField,然后在init方法中将queryset设置为User组(禁止登录的用户):
views.py
class IndexView(LoginRequiredMixin, generic.ListView, generic.edit.FormMixin):
def get_form_kwargs(self):
kwargs = super(IndexView, self).get_form_kwargs()
kwargs.update({'user_id': self.request.user.id})
return kwargs
def get_queryset(self):
return Project.objects.filter(owner=self.request.user.id).order_by('begin_date')
template_name = 'projects/project_index.html'
context_object_name = 'project_list'
form_class = CreateProject
表格
class CreateProject(forms.Form):
contributor_id = forms.ModelMultipleChoiceField(queryset=None, required=False)
def __init__(self, *args, **kwargs):
self.user_id = kwargs.pop("user_id")
super(CreateProject, self).__init__(*args, **kwargs)
self.fields['contributor_id'].queryset = User.objects.exclude(id=self.user_id)
关于python - 使用__init __()中的请求数据以Django形式更改输入的内容,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59716103/