I am using django 1.9. In my settings file, I have added my apps custom context processor as such:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, "templates")],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'social.apps.django_app.context_processors.backends',
'social.apps.django_app.context_processors.login_redirect',
'my_app.context_processors.init',
],
},
},
]
My context_processors.py file in my app is as such:
def init(request):
profile = getattr(request, 'profile', None)
if profile is None:
profile_info = models.Profile.objects.get(user=request.user)
profile = profile_info.user_type
context = {
"profile": profile,
}
return context
In my template, I am calling a helper file to get me the dictionary contents of my custom context file so I can get the users profile type. The helper file is as such:
from django.template import RequestContext
def get_base_context(request):
context = RequestContext(request).dicts[-1] # Last context processor
return context
In my template, when I try to retrieve my custom context, it returns nothing.
def view(request):
c = get_base_context(request)
raise ValueError(c)
returns {}
I don't know what I am doing wrong but if anyone can point it out, I will appreciate it.
The way I want to use this in multiple templates is to get the profile type for the user that logged in.
For example:
{%if profile == "profile1" %}
do something
{% elif profile == "profile2" %}
do something else
{% else %}
do something else 2
{% endif %}
So the reason I am trying to set up the profile via a template context is so I am not querying the user profile type for every view. There might be better ways to do it like perhaps creating a session but I wanted to go with this approach.
Let me know. Thanks