Leonid
Leonid

Reputation: 1157

Django form is not valid without showing any errors

The form, that is described below, is not valid. And expression {{ search_id_form.errors }} doesn't show anything. Django template:

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

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

View:

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

In the view function I handle four different forms on single page. Other forms work correctly. What is the problem here?

Upvotes: 2

Views: 383

Answers (1)

Rahul Gupta
Rahul Gupta

Reputation: 47856

When calling .is_valid, you need to pass the data to search_id_form which you are not doing.

Change

search_id_form = IDSearchForm()

to

search_id_form = IDSearchForm(request.POST)

Upvotes: 1

Related Questions