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>
相关推荐
Andy Dennis16 分钟前
一文漫谈数据库存储之索引(B+, B-link, LSM tree等)
数据库·b+树·lsm-tree
CHANG_THE_WORLD33 分钟前
字符串定义的汇编分析
汇编·数据库
数据知道1 小时前
PostgreSQL:如何通过progres_fdw跨库关联查询?
数据库·postgresql
v***57001 小时前
MYSQL 创建索引
数据库·mysql
heimeiyingwang1 小时前
大模型 RAG 技术原理与企业级落地实践
大数据·数据库·人工智能·架构
倔强的石头_3 小时前
【金仓数据库】ksql 指南(七) —— 启动和管理事务(KingbaseES 数据一致性保障)
数据库
志栋智能3 小时前
自动化运维真的只能选复杂平台吗?
运维·网络·数据库·人工智能·自动化
LaughingZhu4 小时前
Product Hunt 每日热榜 | 2026-02-17
大数据·数据库·人工智能·经验分享·搜索引擎
树码小子4 小时前
Mybatis(16)Mybatis-Plus条件构造器(1)
数据库·mybatis-plus
翔云1234564 小时前
在MySQL中,出现Executed_Gtid_Set 乱序增长的场景
数据库·mysql