Reputation:
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 href="#">
My page top
</a>
<a 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.
Upvotes: 0
Views: 1183
Reputation: 77912
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
.
Upvotes: 1
Reputation: 55
Write the function outside the view, or in another file and import it. Then call the function per view?
create a file "my_view_funcs.py" and write your function. Then import the file into "views.py" and call get_number_of_notifications(self)
Upvotes: 0