Django-从(日期选择器过滤器数据)获取月份和年份

时间:2019-02-28 13:30:39

标签: django django-models django-rest-framework django-forms django-views

这是forms.py

class dateFilter(forms.Form):
date = forms.DateField(input_formats=['%Y-%M-%D'],label='',required=False,
                          widget=forms.DateInput(attrs={
                                                "placeholder": " Select a date",
                                                "class": "dateClass",
                                                "id": "datepicker",
                                                "name": "dateFilter"}))

这是我的views.py

def bsoCharts(request):
#-----------Filter Section------------------------------------------

dateFilter = forms.dateFilter()
FilteredDate = request.POST.get('date')


return render(request, 'BSO/BSO_dashboard2.html', 'dateFilter':dateFilter )

这是我呈现表单的模板:

<div class="container">
        <div class="row">
          <div class="col-12 col-sm-12 col-md-6 col-lg-4">
            <form action="{% url 'BSO:BSO_Dashboard' %}"  method="post" autocomplete="off">
              {% csrf_token %}
              {{dateFilter}}
            </form>
          </div>

        </div>
      </div>

这是我对日期选择器的查询:

<script>
$("#datepicker").datepicker( {
          changeMonth: true,
          changeYear: true,
          showButtonPanel: true,
          dateFormat: 'yy-m-d',
          onSelect: function(dateText, inst) {
        $(this).parents("form").submit();
          }
});

这是日期选择器的照片图像,以及选择日期后的值:

enter image description here

使用以下get方法将结果返回到我的views.py中后:

   FilteredDate = request.POST.get('date')

我想使用以下方法仅获取月份和年份,因此我可以将其用作另一个查询集的过滤器(包含):

   FilteredDate.month

但是,这给了我这个错误:

Django版本:2.1.5 异常类型:AttributeError 异常值:“ str”对象没有属性“ month”

请帮助!

1 个答案:

答案 0 :(得分:0)

request.POST是提交的原始值字典。因此,字段几乎总是字符串(或浮点数/整数)。永远不要代表它们所代表的python值。

在使用Django表单时,您应该始终调用form.is_valid()来清理表单,然后从form.cleaned_data中获取值:

form = forms.dateFilter(request.POST)  # create the form with the data submitted
if form.is_valid():  # check the form is valid (which populates cleaned_data at the same time)
    filtered_date = form.cleaned_data.get('date')  # this is a python date
    if filtered_date:  # since date is optional, check it was passed
        month = filtered_date.month