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 小时前
redis 延迟双删
数据库·redis·缓存
xujiangyan_3 小时前
MySQL的半同步模式
数据库·git·mysql
飞翔沫沫情3 小时前
《MySQL 5.7.44审计合规实践:插件集成与日志分割自动化方案》
数据库·mysql·mysql审计
MXsoft6183 小时前
云原生运维在 2025 年的发展蓝图
运维·服务器·数据库
不辉放弃4 小时前
SQL 主键(Primary Key)
数据库·sql·oracle
qq_339282234 小时前
PostgreSQL-常用命令
数据库·postgresql·oracle
沸材5 小时前
Redis——实现消息队列
数据库·redis·消息队列
しかし1181145 小时前
C语言队列的实现
c语言·开发语言·数据结构·数据库·经验分享·链表
⁤⁢初遇5 小时前
MySQL---数据库基础
数据库
wolf犭良5 小时前
27、Python 数据库操作入门(SQLite)从基础到实战精讲
数据库·python·sqlite