據我瞭解的其他問題:Handle dynamic staticfiles path with Django顯示從標籤文件或context_processors變量在Django模板
我沒有找到解決我的問題的方式。我想在我的HTML模板中插入一個對應於Django查詢的變量。
我已經使用標籤爲了允許取決於用戶組的一些部分。
我tags.py文件看起來像:
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
而我的HTML模板的樣子:
<!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"/>
的目標是在我的tags.py文件,插入拿起變量mytheme
它在我的html模板中。
作爲回報,我越來越所有的時間:
#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
但是,很長一段時間後,搜索的解決方案,並與來自@DanielRoseman在我以前的帖子的慷慨,我沒有找到解。
也許有人有索引或想法?
謝謝
很抱歉,如果這是愚蠢的問題,但是在做自定義標籤,爲什麼你不加'mytheme'在視圖模板背景?像這樣的'context ['mytheme'] = Theme.objects.values_list('favorite_theme')。last()'。此外,如果每個用戶都有自己的主題,那麼不應該爲當前用戶過濾主題:'Theme.objects.filter(user = request.user).values_list('favorite_theme')。last()' – neverwalkaloner
它根本不是愚蠢的問題 !主題必須在我的django網站的任何地方應用。所選主題在所有html模板頁面上更改背景色...。只有管理員(就是說我)可以通過檢查RadioSelectBox來更改主題。如果我把'mytheme'放在視圖中,我必須在所有視圖(大約10個應用程序)中和每個功能上做到這一點?這就是爲什麼標籤文件似乎是一個更好的主意,但我可以犯一個錯誤^^ – Deadpool
好吧,試着修復幾件事情。首先從'GetTheme'中移除參數以避免重寫'Theme' name:'def GetTheme():'。然後在使用之前,在模板中分配'mytheme'變量:'{GetTheme as mytheme%}'。 – neverwalkaloner