Essex
Essex

Reputation: 6128

Displaying variable from tags file or context_processors in Django Template

According to my other question about : Handle dynamic staticfiles path with Django

I am not finding the way to solve my problem. I would like to insert in my HTML template a variable corresponding to a Django query.

I already used tags in order to allow some parts depending on users' groups.

My tags.py file looks like :

from django import template
from django.contrib.auth.models import Group 
from Configurations.models import Theme

register = template.Library() 

@register.filter(name='has_group') 
def has_group(user, group_name):
    group =  Group.objects.get(name=group_name) 
    return group in user.groups.all() 

@register.assignment_tag
def GetTheme(Theme):

    mytheme = Theme.objects.values_list('favorite_theme').last()
    return mytheme

And my HTML template looks like :

<!DOCTYPE html>
<html>
    <head>

    {% load staticfiles %}
    {% load static %}
    {% load user_tags %}

    <title> DatasystemsEC - Accueil </title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <link rel="stylesheet" type="text/css" href="{% get_static_prefix %}{{ mytheme }}/css/Base_Accueil.css"/>

The goal is to pick up the variable mytheme in my tags.py file and insert it in my html template.

In return, I'm getting all the time :

#Look double // in my url
http://localhost:8000/static//css/Base_Accueil.html

#I should get 
http://localhost:8000/static/{{ mytheme }}/css/Base_Accueil.html

But, after a long moment to search a solution and with the generosity from @DanielRoseman in my previous post, I don't find the solution.

Maybe someone had indices or ideas ?

Thank you

Upvotes: 0

Views: 625

Answers (2)

Essex
Essex

Reputation: 6128

I found the solution based on different answers and I will explain what I've done. This solution works for me with Django 1.10 :

First step : Modify settings.py file

I modified my settings.py file and more precisely TEMPLATES PART. For the moment, this modification is just for Accueil Application but I will extend this process to all applications :

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'debug' : DEBUG,
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'myapp.context_processors.context_processors_name_function'],
        },
    },
]

With the following example, the last line will be written like this :

# 'myapp.context_processors.context_processors_name_function'
'Accueil.context_processors.GetTheme'

Second step : Create context_processors.py file in my application

I created this new file in my application part. As above, it will be extend to others applications :

from django.conf import settings
from Configurations.models import Theme

def GetTheme(request):
    return {'mytheme' : Theme.objects.values_list('favorite_theme').last()[0].encode("ascii")}

Third step : Modify my Base.html for Accueil application

I have a base template which manage my Accueil application. I have to write header like this is I want to take account the context_processors variable :

 {% load static %}
 <link rel="stylesheet" type="text/css" href="{% get_static_prefix %}{{ mytheme }}/css/Base_Accueil.css"/>

Through this way, I can pick up the last row from my Theme table and put the variable in {{ mytheme }}. Then, I created my good theme url. Now, Django will search all css file in the good repository.

From now, when I fill the formulary with a choice between two themes : Datasystems and Cameroun and validate my choice, the new theme is taken account and the global background-color change due to my theme choice !

Hopfully my answer will help others programmers !

Thank you for all :)

Upvotes: 2

vinay kumar
vinay kumar

Reputation: 593

you can write custom context_processors.

settings.py

TEMPLATES = [
   {
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [os.path.join(BASE_DIR, 'web', 'templates'),],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.core.context_processors.media',
            'django.core.context_processors.static',
            'django.contrib.messages.context_processors.messages',
            'myapp.contextprocessor.mytheme',
        ],
    },
  },
]

contextprocessor.py

def mytheme(request):
   return {'mytheme': 'red'}

Upvotes: 1

Related Questions