在所有视图中显示来自数据库的动态数据
showing dynamic data from database in all views
我正在使用 Django 2.0
我的 notes
应用程序中有一个模型
notes/models.py
class ColorLabels(models.Model):
title = models.CharField(max_lenght=50)
在所有页面显示的侧边栏导航中,我想显示颜色标签列表,它会显示在所有页面上。
如何在所有视图或所有页面显示动态数据?
使用 custom template context processor.
这会将您需要的上下文(数据)添加到所有视图呈现的模板中。
首先创建上下文处理器(notes/context_processors.py
):
from .models import ColorLabel
def color_labels(request):
return {'color_labels': ColorLabel.objects.all()}
然后将其添加到 settings.py
:
中模板渲染器的 context_processors
option
TEMPLATES = [{
'BACKEND': '...',
'OPTIONS': {
'context_processors': [
'notes.context_processors.color_labels',
...
],
},
}]
最后,您将能够在您的模板中使用它:
templates/base.html
<nav>
{% for color_label in color_labels %}
{{ color_label.title }}
{% endfor %}
</nav>
我正在使用 Django 2.0
我的 notes
应用程序中有一个模型
notes/models.py
class ColorLabels(models.Model):
title = models.CharField(max_lenght=50)
在所有页面显示的侧边栏导航中,我想显示颜色标签列表,它会显示在所有页面上。
如何在所有视图或所有页面显示动态数据?
使用 custom template context processor.
这会将您需要的上下文(数据)添加到所有视图呈现的模板中。
首先创建上下文处理器(notes/context_processors.py
):
from .models import ColorLabel
def color_labels(request):
return {'color_labels': ColorLabel.objects.all()}
然后将其添加到 settings.py
:
context_processors
option
TEMPLATES = [{
'BACKEND': '...',
'OPTIONS': {
'context_processors': [
'notes.context_processors.color_labels',
...
],
},
}]
最后,您将能够在您的模板中使用它:
templates/base.html
<nav>
{% for color_label in color_labels %}
{{ color_label.title }}
{% endfor %}
</nav>