Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initial= not working on Form inputs

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?

like image 256
Daniel Avatar asked Mar 29 '17 10:03

Daniel


1 Answers

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={...})
like image 98
Daniel Avatar answered Sep 28 '22 13:09

Daniel