简体   繁体   English

如何在 Django 过滤器的 DateFromToRangeFilter 中使用自定义 DateRangePicker 小部件

[英]How to use custom DateRangePicker widget with Django Filter's DateFromToRangeFilter

So I have this filter using Django Filter :所以我有这个使用Django Filter

class AssignmentFilter(FilterSet):
    assignment_date = filters.DateFromToRangeFilter()

This built in class of Django Filter generates a form with these two inputs:这个内置的 Django Filter 类生成一个带有这两个输入的表单:

<input type="text" name="assignment_date_after" id="id_assignment_date_0">
<input type="text" name="assignment_date_before" id="id_assignment_date_1">

So there you pick the two dates and based on that it will get you the filtered QuerySet.因此,您可以选择两个日期,并基于此为您提供过滤后的 QuerySet。 All working well.一切正常。

However I would like to use this usefull DateRangePicker: https://www.daterangepicker.com/但是我想使用这个有用的 DateRangePicker: https ://www.daterangepicker.com/

This gets activated like this:这会像这样被激活:

<input type="text" name="dates" class="form-control">

<script>
$('input[name="dates"]').daterangepicker();
</script>

However as you can see, this is only one field where the range between the dates will be set.但是,正如您所看到的,这只是将设置日期之间范围的一个字段。 But Django Filter works with an start input field and end input field.但是Django Filter使用开始输入字段和结束输入字段。

How can I modify this so that I can use the nice widget that belongs to input[name="dates"] .我该如何修改它以便我可以使用属于input[name="dates"]的漂亮小部件。

Maybe a solution is to process it with JavaScript after a GET request.也许一个解决方案是在GET请求之后用 JavaScript 处理它。 The function will then take the start date and inject it into the id_assignment_date_0 field.然后该函数将获取开始日期并将其注入id_assignment_date_0字段。 And take the end date and inject it to the id_assignment_date_1 field.并取结束日期并将其注入id_assignment_date_1字段。 Both the field id_assignment_date_0 and id_assignment_date_1 will be visually hidden then in the form.字段id_assignment_date_0id_assignment_date_1都将在视觉上隐藏然后在表单中。 It seems quite hacky though.虽然它看起来很hacky。

Does anyone have a clever solution for this?有没有人对此有一个聪明的解决方案?

According to this example , you can accomplish what you want like this:根据这个例子,你可以像这样完成你想要的:

<input type="text" id="datePicker" name="dates" class="form-control">
<input type="hidden" name="assignment_date_after" id="id_assignment_date_0">
<input type="hidden" name="assignment_date_before" id="id_assignment_date_1">

<script>
$(function() {
  $('input[name="dates"]').daterangepicker({
    opens: 'left'
  }, function(start, end, label) {
    $('#id_assignment_date_0').val(start)
    $('#id_assignment_date_1').val(end)
  });
  $('#datePicker').removeAttr('name');
});
</script>

Although, the format might differ from what you need.虽然,格式可能与您需要的不同。 You can also change the format with something like below:您还可以使用以下内容更改格式:

$('#id_assignment_date_0').val(start.format('YYYY-MM-DD'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM