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>
相关推荐
wangcheng869919 分钟前
Oracle常用函数-日期时间类型
数据库·sql·oracle
zizisuo21 分钟前
面试篇:Spring Security
网络·数据库·安全
一只fish37 分钟前
MySQL 8.0 OCP 1Z0-908 题目解析(2)
数据库·mysql
StarRocks_labs39 分钟前
从InfluxDB到StarRocks:Grab实现Spark监控平台10倍性能提升
大数据·数据库·starrocks·分布式·spark·iris·物化视图
搞不懂语言的程序员1 小时前
Redis的Pipeline和Lua脚本适用场景是什么?使用时需要注意什么?
数据库·redis·lua
王RuaRua1 小时前
[数据结构]5. 栈-Stack
linux·数据结构·数据库·链表
Lw老王要学习3 小时前
Linux数据库篇、第一章_02_MySQL的使用增删改查
linux·运维·数据库·mysql·云计算·it
林下清风~3 小时前
MySQL——九、锁
数据库·mysql
呦呦鹿鸣Rzh4 小时前
redis
数据库·redis·缓存
xiaogai_gai4 小时前
有效的聚水潭数据集成到MySQL案例
android·数据库·mysql