I have created a application in which i want to filter table between dates (from and to date) but i am not getting desired out put... Please guide me

27 views
Skip to first unread message

neha bhurke

unread,
Feb 16, 2021, 8:58:44 AM2/16/21
to Django users
hi Everyone ,

I have created a application in which I want to  filter table between dates (from and to)dates 
But not getting a desired output .

This is my models.py

class data(models.Model):
machinename = models.CharField(max_length=100)
activity = models.CharField(max_length=255)
description = models.CharField(max_length=500)
datetime = models.DateField()


This is my html page

<form method="POST">
{% csrf_token %}
<center>


<input type="text" id="search_all" placeholder="Search Machine.." style="width:250px; height:30px">
<hr/>

From :<input type="date" name="fromdate"/>
To :<input type="date" name="todate"/>
<input type="submit" value="Search" />
<hr/>

<br>
<div style="width:550px; height:350px; overflow:auto; ">
<table border="4" bgcolor="grey">
<thead>
<tr style="text-align:center; color:black; border:1px solid black; background-color: #f1f1f1;">
<th>Datetime</th>
<th>Machine Name</th>
<th>Activity</th>
<th>Description</th>

</tr>
</thead>
<tbody>
{% for results in formdata %}
<tr style="text-align:center; color:black; border:1px solid black">
<td>{{results.datetime}}</td>
<td>{{results.machinename}}</td>
<td>{{results.activity}}</td>
<td>{{results.description}}</td>

{% endfor %}
</tr>
</tbody>
</table>
</center>
</form>

This is my views.py 

def showresults(request):
if request.method == "POST":
fd = request.POST.get['fromdate']
td = request.POST.get['todate']
search = data.objects.filter(Q(datetime__gte=fd) & Q(datetime__lte=td))
d = {'search': search, 'fd': fd, 'td': td}
return render(request, 'dashboard.html', d)
else:
result = data.objects.all()
return render(request, 'dashboard.html', {'formdata': result})


Please help me..
Thank You !!

Jim Illback

unread,
Feb 16, 2021, 10:54:54 PM2/16/21
to Django Users
Neha, try changing your template for loop from:
{% for results in formdata %}

To:
{% for results in search %}

The name of your queryset in your context (d = {'search': search, 'fd': fd, 'td': td}) is search, not formdata.

Also, I’d recommend improving your names. Things like “data”  and “results” are not the most meaningful names to use.


Good luck!
Jim

neha bhurke

unread,
Feb 17, 2021, 4:10:32 AM2/17/21
to Django users
tysm sir
Reply all
Reply to author
Forward
0 new messages