The reason for my wanting to serve the same view at every URL endpoint, is because the view sends Notification information to the authenticated user.
For example, here is the view which has data that I would like served in every page:
class NotificationsView(View):
def get(self, request, *args, **kwargs):
profile = Profile.objects.get(user__username=self.request.user)
notifs = profile.user.notifications.unread()
return render(request, 'base.html', {'notifs': notifs})
I'm trying to send the context variables into my template to be used with javascript. The JS file lives apart from the template, so I'm attempting to declare the global JS vars in the base template first, then use them in the JS file.
base.html:
...
{% include "landing/notifications.html" %}
<script src="{% static 'js/notify.js' %}" type="text/javascript"></script>
{% register_notify_callbacks callbacks='fill_notification_list, fill_notification_badge' %}
landing/notifications.html:
<script type="text/javascript">
var myuser = '{{request.user}}';
var notifications = '{{notifs}}';
</script>
notify.js:
...
return '<li><a href="/">' + myuser + notifications + '</a></li>';
}).join('')
}
}
Based on this code, you can see how I've ended up in a predicament where I need to use the CBV to send the proper notifications to the landing/notifications.html in order to make sure the javascript variables can be dynamically rendered for the JS file.
I am utterly confused as to how the URL is supposed to be wired up.
As something like this:
url(
regex=r'^notes$',
view=views.NotificationsView.as_view(),
name='home'
),
restricts me to a specific endpoint ("/notes").
How would you suggest I get around this?
This looks like a good use for context processors! They add context variables across your whole project, regardless of the view and route. Here's some reading and sample code that might help:
https://docs.djangoproject.com/en/2.0/ref/templates/api/#django.template.RequestContext
https://docs.djangoproject.com/en/2.0/topics/templates/#configuration
myproject.context_processors.py
def notifications(request):
try:
profile = Profile.objects.get(user__username=self.request.user)
return {'notifs': profile.user.notifications.unread()}
except Profile.DoesNotExist:
return {}
myproject.settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates', # default
'DIRS': [], # default
'APP_DIRS': True, # default
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug', # default
'django.template.context_processors.request', # default
'django.contrib.auth.context_processors.auth', # default
'django.contrib.messages.context_processors.messages', # default
'myproject.context_processors.notifications' # your context processor
]
}
}
]