Django; How To Organize Common Functions Or Similar Templates
I'm a beginner. I've been working on Django project. Now I'm trying to create notification part and I get the count of notifications.
The notification part is on like mypage. There are list menu on mypage and the part is common. Now I want to show up the count on the mypage but I'm wondering if I have to get common context.
there is a common part on pages that are belong to my page.
inbox.html
, my_profile.html
etc.
<div class="list-group">
<a target="_blank" rel="nofollow noreferrer" href="#">
My page top
</a>
<a target="_blank" rel="nofollow noreferrer" href="#">
Inbox
<span class="badge badge-primary badge-pill">{{ this is the count of notifications }}</span>
</a>
The function to get the count of notifications is like this
def get_number_of_notifications(self):
notifications = Message.objects.filter(message_to=request.user, is_read=False).count()
return notifications
and in views.py
is like
def mypage_top(request):
...
def my_profile(request):
...
def inbox(request):
...
My question is basically do I have to write down the process to call the function on each view? I'm wondering if there's a better way.
Answer
Django views are only supposed to return the view-specific data as the template's context (for views using a template of course). To inject "common" data in your template's contexts, there are two main solutions: a context processor or a custom templatetag.
Context processors will be invoked for each and every template (well almost, cf the doc) so it's better to keep them for data that are "cheap" to get and are really useful for all views (typical examples are the auth
and i18n
processors).
For data that have an higher cost and may only be used in some of the templates you rather want a custom templatetag, and that's what I would use here. Don't be scared by the documentation, writing a custom templatetag like this one is really easy using an inclusion_tag
.
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module