priya
priya

Reputation: 53

Filter in django between from date and to date

More pdf file is saved in table with different dates,How to filter pdf file between fromdate and todate.

How to filter inbetween dates and list the pdf file.

views.py

def select_date(request):
    client = Client.objects.all()
    process = Client_Process.objects.all()
    pdf = Client_files.objects.all()
    today = date.today()
    yesterday = today - timedelta(days = 1)
    print(today)
    print(yesterday)
    if request.method == "POST":
        fromdate = request.POST.get('fromdate')
        todate = request.POST.get('todate')
        user = Client_files.objects.filter(Date__range=(fromdate,todate))
        print(user)
    return render(request,'select_date.html', {'pdf':pdf,'client':client,'process':process})


models.py

class Client_files(models.Model):
    Date = models.DateTimeField(default=datetime.now, blank=True)
    client = models.ForeignKey(Client, on_delete=models.CASCADE,null=True)
    client_process = models.ForeignKey(Client_Process, on_delete=models.CASCADE,null=True)
    File_Name = models.FileField()
    Pages = models.IntegerField(null=True)
    Count = models.IntegerField(null=True)
    Status = models.BooleanField(default = False)

    class Meta:
        db_table : 'client_files'

Upvotes: 1

Views: 169

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476719

You should use the __date lookup [Django-doc], to convert a datetime to a date first:

def select_date(request):
    client = Client.objects.all()
    process = Client_Process.objects.all()
    pdf = Client_files.objects.all()
    today = date.today()
    yesterday = today - timedelta(days = 1)
    print(today)
    print(yesterday)
    if request.method == "POST":
        fromdate = request.POST.get('fromdate')
        todate = request.POST.get('todate')
        pdf = Client_files.objects.filter(Date__date__range=(fromdate, todate))
        print(pdf)
    return render(request,'select_date.html', {'pdf':pdf,'client':client,'process':process})

Usually however when you filter items, you pass the parameters as GET parameters in a GET request. A POST request usually changes data.

Upvotes: 2

Related Questions