Django上下文处理器

1创建 (如frontend目录下)category_processors文件:

python 复制代码
def categories(request):
    from backend.models import Category
    category_list = Category.objects.all()
    return {'category_list':category_list}

这里,必须返回一个字典。

2,配置settings.py

python 复制代码
'OPTIONS': {
            'context_processors': [
                'frontend.category_processors.categories',
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.media',
            ],
            'builtins':[
                'django.templatetags.static'

3,header.html使用

html 复制代码
<header>
    <nav>
        <div class="container">
            <div class="logo"><a href="/"></a></div>
            <ul class="nav-menu clearfix">
                <li><a href="/"   class="active" >全部分类</a></li>
                {% for item in category_list %}
                <li><a href="/index/{{ item.pk }}/" >{{ item.catename }}</a></li>
                {% endfor %}
            </ul>
            <div class="shortcut clearfix">
                <a href="/register/" class="a">注册</a>
                <a href="/login/" class="a">登录</a>
            </div>
        </div>
    </nav>
</header>
相关推荐
墨黎芜15 分钟前
SQL Server从入门到精通——C#与数据库
数据库·学习·信息可视化
爱学习的阿磊16 分钟前
持续集成/持续部署(CI/CD) for Python
jvm·数据库·python
一个响当当的名号16 分钟前
lectrue10 排序和聚合算法
数据库
hamawari22 分钟前
SQL语法
数据库·sql·oracle
陌上丨27 分钟前
Redis内存使用率在95%以上,请问是什么原因?如何解决?
数据库·redis·缓存
m0_5613596739 分钟前
使用PyQt5创建现代化的桌面应用程序
jvm·数据库·python
2301_7903009640 分钟前
用Python实现自动化的Web测试(Selenium)
jvm·数据库·python
m0_561359671 小时前
使用Docker容器化你的Python应用
jvm·数据库·python
一条闲鱼_mytube1 小时前
MySQL vs PostgreSQL 对比
数据库·mysql·postgresql