I am getting the date instead of date and time data in a POST request

Issue

I have a date range picker on my website.

When a user inputs the date and time range, I want to send separately within the form the startDate and the endDate

daterangepicker code:

    $('input[name="datetimes"]').daterangepicker({
        timePicker: true,
        timePickerIncrement: 5,
        startDate: moment().startOf('hour'),
        endDate: moment().startOf('hour').add(32, 'hour'),
        locale: {
          format: 'YYYY-MM-DD hh:mm'
        },
        opens: 'center',
        drops: 'auto'
    });

And this is what I tried:

$('#formid').submit(function(e) {
    e.preventDefault();
    let startDate = ($('#datetimes').data('daterangepicker').startDate).format('YYYY-MM-DD hh:mm');
    let endDate = ($('#datetimes').data('daterangepicker').endDate).format('YYYY-MM-DD hh:mm');
    $(this).append('<input type="hidden" name="start_date" value='+startDate+' /> ');
    $(this).append('<input type="hidden" name="end_date" value='+endDate+' /> ');
    this.submit();
});

Before the this.submit(); I did a console.log(startDate) and thi is what I am getting:

enter image description here

I am getting the date and the time (as expected), but then if I try doing a print(request.POST) in the view (django back-end), this is what I get:

enter image description here

Somehow, during the POST the HH:mm disappeared.

How can I keep the values of hh:mm during the POST?

Update:

views.py

def add_new_task(request):
    context = {}
    context['nbar'] = 'index'
    if request.method == 'POST':
        print(request.POST)
    return render(request, 'index.html', context)

models.py

class ToDoList(models.Model):
    title = models.CharField(max_length=60)
    description = models.TextField()
    start_date = models.DateTimeField()
    end_date = models.DateTimeField()
    user = models.ForeignKey(
        User,
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
    )

Solution

This is a long shot, but is it possible that the fact that you’re missing double quotes around the value attributes in your hidden inputs, is what’s causing the issue?

Try changing it to:

$(this).append('<input type="hidden" name="start_date" value="'+startDate+'" /> ');
$(this).append('<input type="hidden" name="end_date" value="'+endDate+'" /> ');

Answered By – 2DH

Answer Checked By – Cary Denson (AngularFixing Admin)

Leave a Reply

Your email address will not be published.