A custom context processor is a Python function that accepts a request object and returns a dictionary of variables that can be used anywhere in the project.
Create a new context_processors.py file in you app directory
from django.contrib.auth.models import AnonymousUser
from .models import DBSpecies
def user_species(request):
if isinstance(request.user, AnonymousUser):
user_species = DBSpecies.objects.none()
else:
user_species = DBSpecies.objects.filter(species_owner=request.user)
return {'user_species': user_species}
AnonymousUser (in case user isn't authenticated): This code first checks if the request.user object is an instance of AnonymousUser. If it is, then the user_species variable is set to an empty queryset using the none() method on the DBSpecies manager. If the request.user object is not an instance of AnonymousUser, then the queryset is filtered based on the species_owner field.
settings.py: add your custom context processor to the context_processor option in settings.py
TEMPLATES = [
{
...
'OPTIONS': {
'context_processors': [
...
'app_fossils.context_processors.user_species',
],
},
},
]
Now you can access user_fossils in any template as a variable. You can even add it to the navbar which isn't taking any requests!
Neat!