Problems with Custom Template Tags in Django 1.8.5

0

Good evening!

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 does not. What 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 a 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, since I'm trying to load it into a base.html file.

So can anyone help with this mystery? Thank you in advance!

    
asked by anonymous 11.02.2016 / 00:55

1 answer

0

You could use custom context_processor . Thus, you will include in the general context, on every page 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 configuration, 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, now on all pages of the application there will be a new item in the context called {{say_hello}} that will print in the "Hello" template.

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

I hope I have helped.

If there are any doubts left, then I'll try to explain.

    
19.03.2016 / 22:28