Problems with Custom Template Tags in Django 1.8.5

Asked

Viewed 40 times

0

Good night!

First, I would like you to help me improve this topic, if necessary.

Well, I work with Django 1.8.5, Python 3.4, virtualenv and other dependencies as well.

My problem is. I have two custom template tags, one works, one doesn’t. The one that works is "companies_i_recommend". Code below:

from django import template
from portalcom.companies.models import Recommend

register = template.Library()


@register.inclusion_tag('companies/templatetags/companies_i_recommend.html')
def companies_i_recommend(user):
    recommendations = Recommend.objects.filter(user=user).count()
    context = {
        'recommendations': recommendations,    
    }    
    return context

@register.assignment_tag
def i_recommend(user, company):
    user = user
    company = company
    recommend = Recommend.objects.filter(user=user, company=company)

In the browser, trying to use tag that does not work, I get a template syntax error saying that the tag is not valid. If I use the Python shell, I get this error:

Traceback (most recent call last):
    File "<console>", line 1, in <module>
ImportError: cannot import name 'i_recommend'

My goal is to put the "recommend" variable in the context of multiple pages, as I am trying to load it into a base.html file..

So, can anyone help with this mystery? Thanks in advance!

1 answer

0

You could use custom context_processor. Thus, you will include in the general context, on all pages what you want.

Create a new file in your app called for example context_processors.py In it write the following code:

def say_hello(request):
    return {
            'say_hello':"Hello",
           }

In your Settings file, in the template setup, include:

TEMPLATES = [
    {
      ...
        'OPTIONS': {
            'context_processors': ["django.contrib.auth.context_processors.auth",
                                    "django.template.context_processors.debug",
                                    "django.template.context_processors.i18n",
                                    "django.template.context_processors.media",
                                    "django.template.context_processors.static",
                                    "django.template.context_processors.tz",
                                    "suaapp.context_processors.say_hello",
                                    ...
]

Ready, with that now on all pages of the application there will be a new item in the context called {{say_hello}} that will print in the template "Hello".

For what you need, just do your method in the context_processors.py file and return what you want to show in the template.

I hope I’ve helped.

If there are any doubts, comment there that I will try to explain.

Browser other questions tagged

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