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>
相关推荐
计算机毕设定制辅导-无忧学长1 小时前
西门子 PLC 与 Modbus 集成:S7-1500 RTU/TCP 配置指南(一)
服务器·数据库·tcp/ip
程序员柳1 小时前
基于微信小程序的校园二手交易平台、微信小程序校园二手商城源代码+数据库+使用说明,layui+微信小程序+Spring Boot
数据库·微信小程序·layui
梦在深巷、2 小时前
MySQL/MariaDB数据库主从复制之基于二进制日志的方式
linux·数据库·mysql·mariadb
IT乌鸦坐飞机2 小时前
ansible部署数据库服务随机启动并创建用户和设置用户有完全权限
数据库·ansible·centos7
IT_10242 小时前
Spring Boot项目开发实战销售管理系统——数据库设计!
java·开发语言·数据库·spring boot·后端·oracle
祁思妙想3 小时前
八股学习(三)---MySQL
数据库·学习·mysql
惊骇世俗王某人3 小时前
1.MySQL之如何定位慢查询
数据库·mysql
秦歌6664 小时前
向量数据库-Milvus快速入门
数据库·milvus
博观而约取5 小时前
Django 数据迁移全解析:makemigrations & migrate 常见错误与解决方案
后端·python·django
Edingbrugh.南空5 小时前
Flink SQLServer CDC 环境配置与验证
数据库·sqlserver·flink