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>
相关推荐
徐子元竟然被占了!!9 小时前
Linux-systemctl
linux·数据库·oracle
YJlio11 小时前
Active Directory 工具学习笔记(10.8):AdInsight——保存与导出(证据留存、共享与二次分析)
数据库·笔记·学习
suoyue_zhan11 小时前
GBase的管理监控平台GEM实践指南
数据库
哈哈老师啊12 小时前
Springboot学生综合测评系统hxtne(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
java·数据库·spring boot
小小8程序员12 小时前
Redis-10
数据库·redis·缓存
liuzhilongDBA12 小时前
从collation mismatch异常到其原理
数据库·version·glibc·postgres·collation
梁萌12 小时前
MySQL数据库分库分表介绍
数据库·mysql·shardingsphere·分库分表
占疏13 小时前
dify API访问工作流/聊天
开发语言·数据库·python
Cat God 00714 小时前
SQL使用及注意事项
数据库·sql·mysql