即使为空,Python Django表单字段输入的长度也为1

时间:2018-11-18 05:34:23

标签: python html django django-templates

我正在使用Python(3.6)和Django(2.1)开发一个项目,在其中需要实现搜索功能。我有两个搜索字段whatwhere。 用户可以为这两个字段输入多个值,并用,分隔它们,然后在用,分割后,我需要检查两个字段的长度。当字段为空时,其长度应为0,但就我而言,即使字段为空,也表明其长度为1

这是我的代码: 从forms.py:

class FetchDataForm(forms.Form):
    what = forms.CharField(max_length=256, required=True)
    where = forms.CharField(max_length=256, required=False)

    class Meta:
        fields = ('what', 'where')

来自templates / search.html:

<form method="POST" action="{% url 'udata:fetch-data' %}">
            {% csrf_token %}
            <div class="form-row">
                <div class="form-group col-md-5">
                    <label for="inputEmail4" style="font-size: x-large">What:</label>
                    <br><span class="help"
                              style="font-size: smaller; padding-top: 0%;"> keywords, or company</span>
                    {% if dd.what %}
                        <input type="text" name="what" value="{{ dd.what }}" class="form-control" id="inputEmail4">
                    {% else %}
                        <input type="text" name="what" class="form-control" id="inputEmail4">
                    {% endif %}
                </div>
                <div class="form-group col-md-5">
                    <label for="inputEmail4" style="font-size: x-large">Where:</label>
                    <br><span class="help"
                              style="font-size: smaller; padding-top: 0%;">City, State or Zip code</span>
                    {% if dd.where %}
                        <input type="text" name="where" value="{{ dd.where }}" class="form-control"
                               id="inputPassword4">
                    {% else %}
                        <input type="text" name="where" value="" class="form-control" id="inputPassword4">
                    {% endif %}
                </div>
                <label for="inputPassword4">&nbsp;</label>
                <br><span class="help" style="font-size: smaller;"> &nbsp;</span>
                <div class="form-group col-md-2">
                    <button type="submit" class="btn btn-primary btn-lg" style="margin-top:10%">Search</button>
                </div>
            </div>

        </form>

然后 来自views.py:

what = form.cleaned_data['what']
where = form.cleaned_data['where']
get_len_what = len(what.split(','))
get_len_where = len(where.split(','))
print('What len is {}'.format(get_len_what))
print('where len is {}'.format(get_len_where))

即使字段为空,它也会将长度打印为1。 这里有什么问题吗?

1 个答案:

答案 0 :(得分:0)

这是一个可行的解决方案:

what = form.cleaned_data['what']
if ',' not in what and len(what) > 0:
    get_len_what = len(what.split(','))
elif ',' in what and len(what) > 0:
    get_len_what = len(what.split(','))
else:
    get_len_what = len(what.split(',')) - 1

而且,我们可以为另一个where实现相同的功能。