应用程式可与ModelChoiceField搭配使用,但不适用于ModelMultipleChoiceField

时间:2019-07-05 15:32:41

标签: django django-forms modelchoicefield modelmultiplechoicefield

我正在尝试在Django页面中检索用户输入数据。但是我无法选择选择字段。我尝试了多种替代方法来解决问题。

  • self.fields ['site']。queryset = forms.ModelMultipleChoiceField(queryset = sites.objects.all())

  • self.fields ['site'] =表格.ModelChoiceField(queryset = sites.objects.filter(project_id = project_id))

  • self.fields ['site']。queryset = form.MultipleChoiceField(widget = forms.SelectMultiple,choices = [(p.id,str(p))for site.objects.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)

我希望得到一个多选字段,但最终出现此错误:

异常值:

“站点”

异常位置: init 中第18行的/home/clyde/Downloads/new/automatic_annotator_tool/django_app/search/forms.py (第18行:self.fields ['site']。queryset = form.MultipleChoiceField(widget = forms.SelectMultiple,choices = [(p.id,str(p))for site.objects.filter(project_id = project_id) )]))

1 个答案:

答案 0 :(得分:0)

您没有正确定义表格。 documentation向您展示了如何执行此操作。

在您的情况下,将是这样的:

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))

您似乎还会混淆常规FormModelForm,因为Meta.model仅在ModelForm中使用,而您正在使用常规Form。建议您在继续之前先阅读一下文档中的区别。