Skip to main content
 首页 » 编程设计

python之没有显示任何错误的 Django 表单无效

2025年05月04日39mfryf

下面描述的表格无效。表达式 {{ search_id_form.errors }} 没有显示任何内容。 Django 模板:

        <form method="POST"> 
            {% csrf_token %} 
            {{ search_id_form.idtype.label_tag }} 
            {{ search_id_form.idtype }} 
            {{ search_id_form.index.label_tag }} 
            {{ search_id_form.index }}<br> 
            <input type="submit" name="id_search_button" value="Submit"> 
        </form> 

Python 类:

class IDSearchForm(forms.Form): 
 
    idtype = forms.ChoiceField( 
        choices=[('idx', 'Our Database ID'), ('uprot', 'UniProt'), ('ncbi', 'NCBI')], 
        initial='idx', 
        widget=forms.RadioSelect, 
        label="Which identifier to use:" 
        ) 
 
    index = forms.CharField(label="Identifier:") 

查看:

def search(request): 
    if request.method == 'POST': 
 
        # handling other forms ... 
 
        # find a toxin by id 
        if 'id_search_button' in request.POST: 
            search_id_form = IDSearchForm() 
            if search_id_form.is_valid(): 
                idtype = search_id_form.cleaned_data['idtype'] 
                index = search_id_form.cleaned_data['index'] 
                return render(request, 'ctxdb/result_ctx.html', { 
                    # here I try to use predefined object to pass to renderer (for debugging) 
                    'ctx': get_object_or_404(CTX, idx='21') 
                    }) 
 
          # handling other forms ... 
 
    # other forms 
    search_id_form = IDSearchForm() 
    # other forms 
 
    return render(request, 'ctxdb/search.html', { 
        # other forms 
        'search_id_form': search_id_form, 
        # other forms 
        }) 

在 View 函数中,我在单个页面上处理四种不同的形式。其他表格工作正常。这里有什么问题?

请您参考如下方法:

调用 .is_valid 时,您需要将数据传递给 search_id_form,而您并没有这样做。

改变

search_id_form = IDSearchForm() 

到

search_id_form = IDSearchForm(request.POST)