I’m learning Django now and have a simple question: how to handle additional page blocks (besides the main content block) in Django?
Let me explain what i mean. Assume we have a page “/news/view/12” which refers to “news.views.view” view function.
At this page i’m going to have blocks like navigation menu, recent blog posts, footer with some info and so on. In other words – these blocks will be placed at every page on the site.
And, of course, there will be the main content block with the content of the news item.
In this view function (“news.views.view”) i want to have a Python code exactly to handle the view of the one piece of news and nothing else:
def view(request, id):
news_item = News.objects.get(pk=id)
return render(request, 'news/view.html', {"item" : news_item})
So, how can i handle another blocks: fetch the data for them and then assign it to the template?
I mean the Python code somewhere in Django, not about templates and its inheritance (i know about it enough).
The most popular and convenient approaches are most appreciable 🙂
As i see you can’t understand me, let me show you solutions that i expect to hear from you.
The first solution is to use decorator functions:
@load_navigation
@load_recent_news
def view(request, id):
news_item = News.objects.get(pk=id)
return render(request, 'news/view.html', {"item" : news_item})
The second solution is to call python function directly in templates:
{% block recent_news %}
{% call "news.views.recent_news" %}
{# this will call a python function which will return rendered template with recent news #}
{% endblock %}
And the third solution is to use django middleware.
But, to tell you the truth, i don’t like any of these approaches. I believe that django has a more convenient way to implement it.
Thank you in advance.
OK,according to your description, I think you can use customized templatetags for the purpose.
Say you want to add recent news in the sidebar (And you have an app called news, while all news stored in a model called Article)
news/templatetags/news.py
base.html
It’s better to start with simple_tag than the complete one as it’s much simpler and fits with most needs.