LouYu
LouYu

Reputation: 691

Initial Value for Form Fields in Django Didn't Work

I'm building a webpage to display a table for a user. I want to provide a form so that user can select displaying how many items per page(and there is also a hidden field to tell the server which page the user is at). I tried to set an initial value for the form, but it didn't work:

class tablePageSettingsForm(forms.Form):
    itemPerPage = forms.ChoiceField(initial = ('20', '20'), label = "item per page", choices = (("10", "10"), ("20", "20")), required = False) #50, 100, 150, 200), initial = 20)
    page = forms.IntegerField(initial = 1, widget=forms.HiddenInput(), required = False)

The python code is here:

if request.method == 'GET':
    form = tablePageSettingsForm(request.GET)
else:
    form = tablePageSettingsForm()

if form.is_valid():
    cd = form.cleaned_data
else:
    raise Http404()
# ...

When I visit this page, I always get Http404.

I put a assert before raise Http404() to check form.['itemPerPage'].errors and form.['page'].errors and found that they are This field is required.

I also tried to change it to:

if form.is_valid():
    cd = form.cleaned_data
else:
    cd = {'itemPerPage': "20", 'page': "1"}

But I still see This field is required. on my page.

Why didn't initial value work?

Upvotes: 0

Views: 59

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599946

The flow here is completely wrong. A form is never valid with only initial data, and you shouldn't raise a 404 if it is invalid. In addition, the request here can only be a GET, so your first if statement makes no sense.

To process a form with GET, you'll need to have something in the submitted data that allows Django to determine that the form has been submitted. So, you might do this in the template:

<form action="." method="GET">
    {{ form }}
    <input type="submit" name="submit" value="Whatever">
</form>

Now, you can switch dependent on whether "submit" is in the data or not:

if "submit" in request.GET:
    form = tablePageSettingsForm(request.GET)
    if form.is_valid():
        cd = form.cleaned_data
        ... do something with cd and redirect ...
else:
    form = tablePageSettingsForm()
return render(request, 'template.html', {'form': form})

Upvotes: 1

Related Questions