不要在Django表单发出的GET请求中包含空白字段

时间:2013-08-23 18:57:04

标签: django django-forms

在我的Django支持的网站上,我有一个包含几个可选字段的搜索页面。搜索页面是Django表单,我的视图功能是典型的:

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()使用提供的字段来查询数据库并呈现响应。我的search.html包括:

<form action="/search/" method="get">{% csrf_token %}
    <!-- Render the form fields -->
    <input type="submit" value="Search" />
    <input type="reset" value="Reset form" />
</form>

由于大多数搜索都有几个空白字段,因此我不想将它们包含在search.html上的提交按钮发出的GET请求中。当前搜索类似于:

http://mysite/search/?csrfmiddlewaretoken=blah&optional_field1=&optional_field2=&optional_field3=oohIWantThisOne

我希望他们看起来像:

http://mysite/search/?csrfmiddlewaretoken=blah&optional_field3=oohIWantThisOne

当然,我还有几个领域。这将是很好的,因为它会使搜索URL更容易人类可解析和共享。

3 个答案:

答案 0 :(得分:4)

您可以将jQuery与按钮触发器一起使用。提供表单并提交按钮ID。

$("#button_id").click(function(){
    $("input").each(function(){
        if($(this).val() == '') {
            $(this).remove();
        }
    });
    $("#form_id").submit();
});

那个(或类似的东西)应该在提交之前删除所有空字段。

答案 1 :(得分:1)

您也可以发布表单。然后构建搜索网址并重定向并删除空值。

答案 2 :(得分:0)

请参见Bill Erickson的Hide empty fields from GET form

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