[Fixed]-Initial Value for Form Fields in Django Didn't Work

1đź‘Ť

âś…

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

Leave a comment