如果没有显示任何错误,Django表单无效

时间:2015-08-31 17:28:25

标签: python django django-forms

下面描述的表单无效。表达式{{ 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
        })

在视图功能中,我在单页上处理四种不同的形式。其他形式正常工作。这有什么问题?

1 个答案:

答案 0 :(得分:1)

调用.is_valid时,您需要将数据传递给您未执行的search_id_form

更改

search_id_form = IDSearchForm()

search_id_form = IDSearchForm(request.POST)