Django Custom Template Tags

Asked

Viewed 535 times

2

Good afternoon, recently I have a problem in the Django framework, I have a problem in my custom template tag, I do the method in a.py file call it in the templates and does not display the result I want, can take a look doing please?

Follow the files:

time_tags.py

from django import template
from datetime import date

register = template.Library()

@register.filter
def informa_data(value):
    today = date.today()
    weekday = today.weekday()
    if weekday == 4:
        return str(today)
    else:
        return 'nao e sexta'

html template.:

Inseri {% load time_tags %} just below the:

{% extends 'base/base.html' %}
{% load staticfiles %}

And somewhere within the <body>:

<p>
     {{ instance.content|informa_data }}
</p>

2 answers

2


After a dialogue, and understanding the real problem we arrived at the following solution:

# views.py
def from_friday_to_friday(now=datetime.now()):
    days_from_friday = (now.weekday() - 4) % 7
    first_friday = now - timedelta(days=days_from_friday)
    myfridays = {
        'first_friday': first_friday,
        'second_friday': first_friday + timedelta(weeks=1)
    }
    return myfridays


def home(request):
    ctx = {'myfridays': from_friday_to_friday()}
    return render(request, 'index.html', ctx)

and the template

# index.html
<p>{{ myfridays.first_friday|date:"d/m/Y" }} à {{ myfridays.second_friday|date:"d/m/Y" }}</p>
  • Dude, the error in your code is not fixed with this code that you put there in the answer. You abandoned the use of your custom template tag instead of fixing it. I found this a little strange, because they had already indicated where was the error of their custom template tag in another reply.

1

I believe your problem is here:

@register.filter
def informa_data(value):
    today = date.today() #MAIS PRECISAMENTE AQUI
    weekday = today.weekday()
    if weekday == 4:
        return str(today)
    else:
        return 'nao e sexta'

in this code you have declared your filter correctly, the filter receives a value as parameter value which is the value of the variable that you apply your filter to in the template {{ instance.content|informa_data }}.

In this example you put the value would be the value of the variable instance.content.

However you are not using the value that is being passed by parameter and using date.Oday(). What makes your filter always return hoje it’s Friday or not.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.