0

why this is not working? I can't concatenate the filter with another variable?

I have a feeling that I'm being very dumb.

I'm new at django and trying a couple of things with the model.

When I use: birthdate__contains='-03-' works fine, but with the variable, nothing shows up at the url

from django.shortcuts import render from .models import Employee from datetime import datetime

# Create your views here.

def index(request):
    currentMonth = datetime.now().month
    mes_atual = '-'+str(currentMonth)+'-'
    employees = Employee.objects.filter(
                                    birthdate__contains=mes_atual
    )
    context = {
        'employees' : employees
    }
    return render(request, 'index.html', context)

thanks in advance

Keval
  • 557
  • 10
  • 15
ddddddd
  • 85
  • 1
  • 10

1 Answers1

0

The output of datetime.now().month will be 3 not 03

To filter you need the date like 03.

currentMonth = datetime.now()
mes_atual = '-' + str(currentMonth.strftime('%m')) + '-'

Refer this answer for info

Your code will be:

def index(request):
    #currentMonth = datetime.now().month
    #mes_atual = '-'+str(currentMonth)+'-'
    currentMonth = datetime.now()
    mes_atual = '-' + str(currentMonth.strftime('%m')) + '-'

    employees = Employee.objects.filter(
                                    birthdate__contains=mes_atual
    )
    context = {
        'employees' : employees
    }
    return render(request, 'index.html', context)
Keval
  • 557
  • 10
  • 15