[Fixed]-How to pass Date Range Picker start and end value to django view.py

1👍

In your example, you are using POST METHOD.

So you need to link your form to your daterangepicker. You don’t do it in your code.

You have your form, and after you created a div with your datepicker.
You can create a form with two datefield.

date_start = forms.DateField(...)

date_end = forms.DateField(...)

And in your javascript code, you can link one datepicker to each field.

Better solution, with Date Range Picker (http://www.daterangepicker.com/), this component can manage two dates in one field. Add to your form one field.

date_range_picker = forms.CharField(...)

It’s a CharField here, because the field will have two dates in a string.
And remove your div where you link your date picker. Link your date picker on your field. Id of your field will be : id_date_range_picker.

<script type="text/javascript">
$(function() {

    var start = moment().subtract(29, 'days');
    var end = moment();

    function cb(start, end) {
        $('#id_date_range_picker span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
    }

    $('#id_date_range_picker').daterangepicker({
        startDate: start,
        endDate: end,
        ranges: {
           'Today': [moment(), moment()],
           'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
           'Last 7 Days': [moment().subtract(6, 'days'), moment()],
           'Last 30 Days': [moment().subtract(29, 'days'), moment()],
           'This Month': [moment().startOf('month'), moment().endOf('month')],
           'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
        }
    }, cb);

    cb(start, end);

});

</script>

Then in your view, you can retrieve POST data. And treat the date_range_picker field to separate the two dates that will surely be in a single string.

Leave a comment