我正在尝试在 django 页面中检索用户输入数据。但我无法选择多项选择领域。我尝试了多种没有缓解的方法。
self.fields['site'].queryset=forms.ModelMultipleChoiceField(queryset=sites.objects.all())
self.fields['site'] = forms.ModelChoiceField(queryset=sites.objects.filter(project_id=project_id))
self.fields['site'].queryset = forms.MultipleChoiceField(widget=forms.SelectMultiple,choices=[(p.id, str(p)) for p in sites.objects.filter(project_id=project_id)])
表格.py
类 SearchForm(forms.Form):
class Meta:
model= images
fields=['site']
def __init__(self,*args,**kwargs):
project_id = kwargs.pop("project_id") # client is the parameter passed from views.py
super(SearchForm, self).__init__(*args,**kwargs)
self.fields['site'] = forms.ModelChoiceField(queryset=sites.objects.filter(project_id=project_id))
视图.py
def site_list(请求,project_id):
form = SearchForm(project_id=project_id)
site_list = sites.objects.filter(project__pk=project_id).annotate(num_images=Count('images'))
template = loader.get_template('uvdata/sites.html')
if request.method == "POST":
image_list=[]
form=SearchForm(request.POST,project_id=project_id)
#form=SearchForm(request.POST)
#site_name=request.POST.get('site')
if form.is_valid():
site_name=form.cleaned_data.get('site')
print(site_name)
我希望得到一个多选字段,但我最终得到了这个错误:
异常值:
'地点'
异常位置:/home/clyde/Downloads/new/automatic_annotator_tool/django_app/search/forms.py init,第 18 行(第 18 行:self.fields['site'].queryset = forms.MultipleChoiceField(widget=forms.SelectMultiple , 选择=[(p.id, str(p)) for p in sites.objects.filter(project_id=project_id)]))