In the last few months, I'm building my first project with Django. It is a project about solvents tracking and a control system of air pollution for the tannery industry. Soon I will make a series of posts in which I will explain my approach to the project.
Now, I want to take note of a new thing I've learnt working with this project.
First of all, I want to thanks Gilbish because I solved my problem reading his post regarding Context Processors.
Ok, let's go.
The problem
After building the database and a draft of the front end, I have to take the name of the company that is using my program and put it in the navbar of the base.html page, so it will be shown in every page.
The Django Documentation took me to "Context Processor" subject so I tried to do some experiments. Finally, I found this post written by Gilbish and I tried to apply it to my case.
First Step
First of all, in models.py I have a Model for the company's data:
class Company(models.Model):
company_name = models.CharField(max_length=100)
vat_number = models.CharField(max_length=11)
...
Second Step
In Django Documentation context processors are explained as:
context_processors is a list of dotted Python paths to callables that are used to populate the context when a template is rendered with a request. These callables take a request object as their argument and return a dict of items to be merged into the context.
So we can build our custom context processor that will return a dictionary with the variable we need.
To do this, we can create a new file in our app folder, call him context_processors.py and write the function to get the data we need.
from .models import Company
def get_company_name(request):
company_name = Company.objects.all()
return {'company_name': company_name[0]}
Third Step
Now we have to add the path of our custom context processor to settings.py file in the Template section:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
os.path.join(BASE_DIR, 'templates'),
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
#path of our custom context processors
'myapp.context_processors.get_company_name',
],
},
},
]
Ok. Now, we can use our variable in all the templates.
But, how can we use it?
In my case, I put the variable in the base.html file that will be extended in other templates.
<a class="navbar-brand col-md-3 col-lg-2 mr-0 px-3" href="#">{{ company_name }}</a>
As I said, this post is like a simple note for me, but I hope it can help.
Please feel free to add comments and suggestions.
Top comments (2)
nice post, thanks for mentioning me 😄
Your post helps me a lot!