Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

277
Visualizações
Is it better to use Django template tags or pass variables from python

I'm displaying a date on a Django template, and I have a python function that formats the date today for me and passes it to my template.

# function [format example: Wednesday 01 February 10:00:00]
def today():
    date_now = datetime.now()
    day_number = date_now.strftime("%d")
    month_name = date_now.strftime("%B")
    day_name = date_now.strftime("%A")
    time = date_now.strftime("%X")
    date = "{} {} {} {}".format(day_name, day_number, month_name, time)
    return date

# view
def myview(request):
    the_date_today = today()
    context = {
        "the_date_today": the_date_today,
    }
    return render(request, "template.html", context)

# template
<h1>{{ the_date_today }}</h1>

I've just found a way of doing this just with Django template tags.

# view
def myview(request):
    the_date_today = datetime.now()
    context = {
        "the_date_today": the_date_today,
    }
    return render(request, "template.html", context)

# template
<h1>{{ the_date_today|date:"l m F H:i" }}</h1>

What's the better approach for this? It's a lot less code to just use template filters, but does this make anything slower?

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The template method is better. It's not going to be slower.

If later on you need to modify the display format you can do so by simply modifying the template, not the code.

What's more, you don't even need to pass the value for the_date_today to the template because you can call now in the template:

<h1>{% now "l d F H:i" %}</h1>
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda