I have a simple search form on my page /
.
class SearchForm(Form):
query = CharField(max_length=256,
label="Search",
required=False,
widget=TextInput(attrs={'placeholder': 'Search …',
'class': 'form-control'}))
page = IntegerField(min_value=8, initial=1, widget=HiddenInput())
sort = CharField(max_length=16, initial="id", widget=HiddenInput())
order = CharField(max_length=4, initial="asc", widget=HiddenInput())
My (simplified) view is this:
def search(request):
search_form = SearchForm(request.GET)
return render(request, "search.html", {'search_form': search_form})
My goal is to have search_form.cleaned_data['<FIELD>']
return the initial values I set in the class SearchForm
, without having to check wether they are exist None
or are empty ''
.
Unfortunately my code does not work as the input elements are renderd like this:
<input id="id_page" name="page" type="hidden" />
<input id="id_sort" maxlength="16" name="sort" type="hidden" />
<input id="id_order" maxlength="4" name="order" type="hidden" />
Any ideas?
The reason the code would not work was because
search_form = SearchForm(request.GET)
creates a bound form. And bound forms don't have initial values.
I ended up with this gem. It checks if request.GET
contains at least one of the form's fields (regardless of value, e. g. /?page=
) and then creates a bound form where validation can happen. Otherwise the user visited /
or submitted other parameters not related to the form (e. g. /?foo=bar
).
if request.GET & SearchForm.base_fields.keys():
search_form = SearchForm(request.GET)
else:
...
search_form = SearchForm(initial={...})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With