Friday, 23 August 2013

Don't include blank fields in GET request emitted by Django form

Don't include blank fields in GET request emitted by Django form

On my Django-powered site, I have a search page with several optional
fields. The search page is a Django form, and my view function is the
typical:
def search(request):
form = SearchForm(request.GET or None)
if form.is_valid():
return form.display_results(request)
return render(request, 'search.html', {'form': form})
Form.display_results() uses the fields that are provided to query the DB
and render a response. My search.html includes:
<form action="/search/" method="get">{% csrf_token %}
<!-- Render the form fields -->
<input type="submit" value="Search" />
<input type="reset" value="Reset form" />
</form>
Since most searches will have several blank fields, I'd like not to
include them in the GET request emitted by the submit button on
search.html. Current searches look something like:
http://mysite/search/?csrfmiddlewaretoken=blah&optional_field1=&optional_field2=&optional_field3=oohIWantThisOne
And I'd like them to look like:
http://mysite/search/?csrfmiddlewaretoken=blah&optional_field3=oohIWantThisOne
Of course, I have a several more fields. This would be nice to have
because it would make search URLs more easily human-parsable and sharable.

1 comment:

  1. You could use jQuery with an button trigger. Give the form and submit button ids.

    $("#button_id").click(function(){
    $("input").each(function(){
    if($(this).val() == '') {
    $(this).remove();
    }
    });
    $("#form_id").submit();
    });
    That (or something similar) should remove all the empty fields before the submit.

    ReplyDelete