Pass value of Dateinput to variable in Django

0

... I'm a bit of a rookie in this django, I know how to do this kind of javascript queries, yii, jquery but in django it's a bit complicated for me.

Creating a search by range of dates, because I want to keep track of income for weeks, months, quarters and semesters, in django I've come across this:

when I consult the database

ingresos.objects.filter(fecha__range=(f_inicial, f_cierre)

I want f_initial and f_close to take the date value that I choose in the Dateinput that I define in the Form, how can I do this, thanks

    
asked by Roly Miranda Díaz 06.04.2017 в 18:52
source

1 answer

1

Because what you receive from your form is a string, you must convert this same datetime object that you can use as a parameter for your searches

Assuming that what you receive from your front end, is formatted in dd / mm / yyyy

in your view:

 import datetime

 def mi_vista(request):
     f_inicial = request.POST.get("f_inicial")
     f_inicial_a_datetime = datetime.datetime.strptime(f_inicial, '%d/%m/%Y')
     # lo anterior te genera un objeto datetime por ejemplo
     # datetime.datetime.strptime("31/03/2017", "%d/%m/%Y")
     # datetime.datetime(2017, 3, 31, 0, 0)

     # hacemos lo mismo con fecha de cierre
     f_cierre = request.POST.get("f_cierre")
     f_cierre_a_datetime = datetime.datetime.strptime(f_cierre, '%d/%m/%Y')

     # y ahora si puedes aplicarlo a tus busquedas

     Ingresos.objects.filter(fecha__range=(f_inicial_a_datetime, f_cierre_a_datetime))

     # En vista de que el objeto date time te devolvera la fecha desde la hora 0
     # si deseas solo la fecha del objeto obtenido puedes hacerlo con f_inicial.date() o f_cierre.date()

I hope it helps!

    
answered by 09.04.2017 / 19:47
source