python - 传递给模板引擎的 Python/Django 通用方法
问题描述
我有一个已经有数百个视图的大型 Django 项目。我正在创建一个tasks
功能,用户可以在其中完成与他们正在使用的项目中的特定应用程序相关的特定任务。我有多个界面(也就是项目中的 Django 应用程序):、、、admin
等等management
……onsite
每个界面都有自己的导航和tasks
链接。
task
如果用户处于尚未完成的界面中,我想要的是能够更改此链接的颜色。
这很容易在每个视图中检查,然后我可以根据传递到视图中的变量普遍地为链接渲染正确的颜色,但是对于数百个视图来说这是非常乏味的。
我想我可以在每个界面/Django App 中添加一个过滤器来简化这一点,但这是最简单的解决方案吗?
这是我想在每个界面的导航中调用的方法的示例:
from objects_client.task_models.task_models import Tasks
def does_interface_have_open_tasks(current_interface, db_alias):
if Tasks.objects.using(db_alias)\
.filter(interface=current_interface, completed=0).exists():
return True
return False
解决方案
我最终使用 aContext Processor
来解决我的需求,如下所示:
import traceback
from objects_client.task_models.task_models import Tasks
def universally_used_data(request):
# I use multiple DBs
db_alias = request.session.get('db_alias')
# dictionary for global context values
dictionary_to_return = dict()
# interfaces and URL equivalents
interface_dictionary = {
'adm': 'admin',
'mgt': 'management',
'onsite': 'onsite',
'secu': 'security',
'maint': 'maintenance'
}
try:
# get interface url
short_url = request.path[1:-1].split('/')[1]
# get interface from dictionary above
interface = interface_dictionary.get(short_url)
dictionary_to_return['SHORT_URL'] = short_url
dictionary_to_return['INTERFACE'] = interface
# see if there is an open task...
if Tasks.objects.using(db_alias) \
.filter(interface=interface, completed=0).exists():
dictionary_to_return['OPEN_TASKS'] = True
else:
dictionary_to_return['OPEN_TASKS'] = False
except Exception as ex:
print(ex, traceback.format_exc())
return dictionary_to_return
这是我加载的方式Context Processor
:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'templates'),
...
]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
...
# custom processors
'utils.context_processors.context_processors.universally_used_data'
],
},
},
]
然后我可以像这样在模板中调用 this 变量来更改 HTML 元素的颜色,no{% load [whatever] %}
或任何东西:
{% if OPEN_TASKS %}
style="color:red;"
{% endif %}
感谢@Daniel Roseman的建议/评论。这让我有点难过:)
推荐阅读
- java - 我的进度对话框卡在登录屏幕上并且没有开始新活动
- javascript - 并行执行带返回值的 Promise
- ionic-framework - 如何在 ionic 3 中使用选项卡正确设置我的主应用程序?
- angular - 即使在页面以角度5重新加载后如何将值本地存储到变量中
- airflow - Apache Airflow - 用户管理和多租户
- angular5 - 出现错误 TS2339:角度 5 和 graphQL 和 apollo 中的属性“数据”
- haskell - 声明 foo (5+5:x:xs) = x 中的模式解析错误
- javascript - 使用 JQuery 的 load(file.php) 方法时,不会加载所选 php 文件的 Javascript
- haskell - 为什么这个函子定义给我一个错误?
- reactjs - 在 react-cropper 中设置最小图像分辨率