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

6👍

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.

👤Rob L

2👍

You could also POST the form. Then build the search url and redirect with empty values removed.

👤Rob L

2👍

disclaimer: This is a very old question, and the only one I could find that matches the problem I ran into. It’s entirely possible that my solution didn’t exist at the time, and an even better way has since been added.

I’m using Django 3.2. I didn’t want to use js/jQuery, nor did I want to use a POST form, so here’s what I came up with. In a nutshell, it just checks the GET data to see if there are any default values present, and simply redirects to a URL that doesn’t have them.

In your view:

from django.shortcuts import redirect

def myView(request):
    if not is_clean_form(request.GET):
        return redirect(whatever_url_path + clean_url_parameters(request.GET))
    else:
        # whatever your view does normally

Helper functions (consider making these static methods of your Form class, to keep all that type of stuff together):

from urllib.parse import urlencode

# fields and their default value (eg. empty string)
default_form_values = [
    ("some_field_name", ""),
    # ...
]

def is_clean_form(form_dict):
    for field, default_value in default_form_values:
        if field in form_dict and form_dict[field] == default_value:
            return False
    return True

def clean_url_parameters(form_dict):
    return "/?" + urlencode([
        (field, form_dict[field]) for (field, default_value) in default_form_values
        if field in form_dict and form_dict[field] != default_value
    ])
👤SeaJay

1👍

See Hide empty fields from GET form by Bill Erickson:

jQuery(document).ready(function($){

  // Remove empty fields from GET forms
  // Author: Bill Erickson
  // URL: http://www.billerickson.net/code/hide-empty-fields-get-form/

  // Change 'form' to class or ID of your specific form
  $("form").submit(function() {
    $(this).find(":input").filter(function(){ return !this.value; }).attr("disabled", "disabled");
    return true; // ensure form still submits
  });

  // Un-disable form fields when page loads, in case they click back after submission
  $("form").find(":input").prop("disabled", false);
}
👤seberm

Leave a comment