Django Custom Template Tags

1

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 and I call it in templates and it does not display the result I want, can take a look 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'

template.html:

Inserted {% load time_tags %} just below:

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

And somewhere in the <body> :

<p>
     {{ instance.content|informa_data }}
</p>
    
asked by anonymous 06.06.2016 / 22:59

2 answers

2

After a dialogue, and understanding the real problem we arrive 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>
    
08.06.2016 / 04:24
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 is given a value as value parameter which is the value of the variable you apply your filter in the {{ instance.content|informa_data }} template.

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

However you are not using the value being passed by parameter and using date.today (). What causes your filter to always return if hoje is Friday or not.

    
07.06.2016 / 08:23