How to manage common sections in Django?
author
,
Aspirant Programmer

Suppose we have some section in base template which loads in all pages, So how to manage in Django. What is the name of feature that is used to overcome this problem?

  • Total 1 Answer
  • 306
Can You answer this question?
author
,
Aspirant Programmer

To overcome the above shared problem, we use "Custom template tags" feature of Django. It is one of the great feature to handle common section which gets display in base.html template and be available in all templates those are using base template. Suppose there is a section to display about text in sidebar and you want to write code once and use it in all templates without calling it in all views.py functions. The custom template tags work only if your app is included into the INSTALLED_APPS of settings.py file. Follow below steps to get it done:

1- Create a directory "templatetags" in your app same level like templates, static etc. and don't forget to create __init__.py file into this folder so, django can treat it as django package folder and load its modules.

2- Create another file Ex. "common_feature.py" and write below line of code to fetch about us object.

from django import template
from tnews.models import Cms

register = template.Library()

@register.simple_tag
def about_section():
    return Cms.objects.get(pk=1)

 

And now go to the template file Ex. sidebar.py and load this created template tag as {% load common_feature %}  and use

{% about_section as about %} it will contain object of the about us record.

After creating the module you will need to restart your server and  access all attributes of that record easily.

For further, reference go to the below Django documentation:

https://docs.djangoproject.com/en/2.1/howto/custom-template-tags/