我正在尝试在Django页面中检索用户输入数据。但是我无法选择多级字段。我尝试了多种替代方案,以免缓解。
-
self.fields ['site']。querySet = forms.modelmultiplechoicefield(querySet = stites.object.all(((
-
self.fields ['site'] = forms.modelchoicefield(queryset = stites.objects.filter(project_id = project_id((
-
self.fields ['site']。querySet = forms.multipliplechoicefield(widget = forms.selectmultiple,choce = [(p.id,str(p(for p in sites.object.objects.filters.filters.filterss.filter(project_ID(= project_id((((
forms.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))
views.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/search/forms.py in init ,第18行(第18行:self.fields ['site']。querySet = forms.multipliplechoicefield(widget = forms.selectmultiple,choce = [(p.id,str(p((p in sites.object.objects.filters.filters.filter(project_id = project_id = project_id = project_id = project_id =((((
您无法正确定义您的表格。该文档向您展示了如何执行此操作。
在您的情况下,这将是这样的:
class SearchForm(forms.Form):
site = forms.ModelMultipleChoiceField(queryset=Sites.object.none())
def __init__(self,*args,**kwargs):
project_id = kwargs.pop("project_id")
super(SearchForm, self).__init__(*args,**kwargs)
self.fields['site'].queryset = Sites.objects.filter(project_id=project_id))
您似乎也使常规Form
和ModelForm
混淆,因为Meta.model
仅在ModelForm
中使用,而您使用的是常规Form
。我建议您在继续之前阅读文档的差异。