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>
相关推荐
薛定谔的算法14 小时前
phoneGPT:构建专业领域的检索增强型智能问答系统
前端·数据库·后端
Databend15 小时前
Databend 亮相 RustChinaConf 2025,分享基于 Rust 构建商业化数仓平台的探索
数据库
得物技术16 小时前
破解gh-ost变更导致MySQL表膨胀之谜|得物技术
数据库·后端·mysql
c8i20 小时前
drf初步梳理
python·django
Raymond运维21 小时前
MariaDB源码编译安装(二)
运维·数据库·mariadb
沢田纲吉21 小时前
🗄️ MySQL 表操作全面指南
数据库·后端·mysql
RestCloud2 天前
SQL Server到Hive:批处理ETL性能提升30%的实战经验
数据库·api
RestCloud2 天前
为什么说零代码 ETL 是未来趋势?
数据库·api
ClouGence2 天前
CloudCanal + Paimon + SelectDB 从 0 到 1 构建实时湖仓
数据库
c8i2 天前
django中的FBV 和 CBV
python·django