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

Raf Rasenberg :

So I have this filter using Django Filter:

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

This built in class of Django Filter generates a form with these two inputs:

<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. All working well.

However I would like to use this usefull 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.

How can I modify this so that I can use the nice widget that belongs to input[name="dates"].

Maybe a solution is to process it with JavaScript after a GET request. The function will then take the start date and inject it into the id_assignment_date_0 field. And take the end date and inject it to the id_assignment_date_1 field. Both the field id_assignment_date_0 and id_assignment_date_1 will be visually hidden then in the form. It seems quite hacky though.

Does anyone have a clever solution for this?

nima :

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'))

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=11769&siteId=1