0

I'm trying to get validation running on a django form used to retrieve a list of objects in a ListView View. Despite having read django docs and many other questions here, I can't find out what's wrong in this simple test code:

form.html

<form action="list.html" method="get">
    {{ form }}
    <input type="submit" value="Submit">
</form>

list.html

<ul>
    {% for area in object_list %}
        <li>{{ area.name }}</li>
    {% endfor %}
</ul>

forms.py

from django import forms

class SearchArea(forms.Form):
    area = forms.CharField(label='Area code', max_length=6)

    def clean_area(self):
        area = self.cleaned_data['area'].upper()
        if '2' in area:
            raise forms.ValidationError("Error!")
        return area

views.py

class HomePageView(FormView):
    template_name = 'form.html'
    form_class = SearchArea

class AreaListView(ListView):
    template_name = 'list.html'
    model = AreaCentral

    def get_queryset(self):
        q = self.request.GET.get('area')
        return AreaCentral.objects.filter(area__istartswith=q)

When I try to submit something like "2e" I would expect a validation error, instead the form is submitted. Moreover I can see in the GET parameters that 'area' is not even converted to uppercase ('2E' instead of '2e').

1 Answers1

0

The default a FormView will only process the form on POST; the GET is for initially displaying the empty form. So you need to use method="post" in your template form element.

Your action attribute is also suspect; it needs to point to the URL of the form view. If that actually is the URL, note it's not usual to use extensions like ".html" in Django URLs, and I would recommend not doing so.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895