0

I have an HTML form which returns me two dates in a format like this: 2019-10-15. When I checked the type() of the date return it came out to be "str"

how can I use this string in my Django query?

Code:

start = request.POST['from']
end = request.POST['to']

foo = bar.objects.filter(dispatch_date = ??)

3 Answers 3

2

You can use the range for filtering with date

You can convert string in to date by using the parse_date like this.

from django.utils.dateparse import parse_date
start = request.POST['from']
start_date = parse_date(start)

end = request.POST['to']
end_date = parse_date(end)


foo = bar.objects.filter(date__range=(start_date,end_date))

parse_date function will return None if given date not in %Y-%m-%d format so in this case you can convert into date like this

start = request.POST['from']
start_date = datetime.datetime.strptime(start, "%Y-%m-%d").date()
Sign up to request clarification or add additional context in comments.

1 Comment

The first solution i.e. without parsing the date works fine, thanks
1

You have to convert the date in required format according to Model like:

start = request.POST['from']
end = request.POST['to']

start_date = datetime.strptime(start, "%Y-%m-%d %H:%M:%S.%f")

end_date = datetime.strptime(end, "%Y-%m-%d %H:%M:%S.%f")

foo = bar.objects.filter(date__range=[start_date, end_date])

"%Y-%m-%d %H:%M:%S.%f is the format you have to update according to your Model, how you defined the field.

Comments

1

VIEWS.PY

   def date_page(request): 
    f_date = request.GET.get("f_date")
    t_date = request.GET.get("t_date")


    date_queryset = Add.objects.filter(date__range=(f_date, t_date))
    for i in date_queryset:
        print (i.budget, i.date)

    return render (request , 'date_page.html',{'date_queryset':date_queryset})

HTML

    <form method="GET"> {% csrf_token %}

FROM  : <input type="date" name="f_date"> <br>  <br>  

            TO    :  <input type="date" name="t_date"> <br>  <br>  <hr>


    <input type="submit"> <br> <br>

    </form>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.