zoukankan      html  css  js  c++  java
  • Django 模板 自定义context_processors

    Django版本

    1.8.4

    为什么要自定义context_processors

    在做博客的过程中,在浏览排行,评论排行,标签,文章归档,友情链接等内容每一个显示页面都是要显示的。如果在每一个views的处理函数当中都返回以上信息,这就造成了严重的代码冗余。因此就把他们设置成所有的模板视图都能够访问,这有点像全局变量。

    知识上的准备

    在Django中可以通过设置context_processors,使到每一个模板视图被渲染时,都传相对应的Context值。

    步骤

    1.全局Context返回函数

    在myApp下,创建context_processors.py文件, 并创建函数。

    def global_setting(request):
        # 文章归档数据
        archive_list = Article.objects.distinct_date()
        .......
        return locals()
    
    2. 修改settings.py

    在TEMPLATES中的context_processors列表当中添加该自定义的global_setting函数,添加过后,当每一次进行模板视图渲染时,都会把在函数global_setting中对应的Context传递到模板视图中。另外的不创建context_processors.py文件也可以,只要把自定义的函数路径加入到context_processors就可以了,但是那样不方便管理,不推荐那样做

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, 'blog/templates')]
            ,
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.contrib.auth.context_processors.auth',
                    'django.template.context_processors.debug',
                    'django.template.context_processors.i18n',
                    'django.template.context_processors.media',
                    'django.template.context_processors.static',
                    'django.template.context_processors.tz',
                    'django.contrib.messages.context_processors.messages',
    
                     # 全局上下文信息
                    'blog.context_processors.global_setting',
                ],
            },
        },
    ]
    
    3. 视图逻辑

    通过render_to_response()渲染时,需要指定context_instance=context_instance=RequestContext(request)
    ,若不指定全局的Context将不会传递给相对于的模板视图, 通过render()渲染就不需要指定context_instance

    def index(request):
        try:
            # 最新的文章数据,并分页
            article_list = get_page(request, Article.objects.all(), number=10)
        except Exception as e:
            logger.error(e)
        return render(request, 'index.html', locals())
    

    参考

    1. https://docs.djangoproject.com/en/1.8/ref/templates/upgrading/
    2. https://docs.djangoproject.com/en/1.8/topics/templates/
    3. http://djangobook.py3k.cn/2.0/chapter05/


    作者:Ljian1992
    链接:https://www.jianshu.com/p/fa558c8d14cb
    來源:简书
    简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。
  • 相关阅读:
    BNU 51002 BQG's Complexity Analysis
    BNU OJ 51003 BQG's Confusing Sequence
    BNU OJ 51000 BQG's Random String
    BNU OJ 50999 BQG's Approaching Deadline
    BNU OJ 50998 BQG's Messy Code
    BNU OJ 50997 BQG's Programming Contest
    CodeForces 609D Gadgets for dollars and pounds
    CodeForces 609C Load Balancing
    CodeForces 609B The Best Gift
    CodeForces 609A USB Flash Drives
  • 原文地址:https://www.cnblogs.com/ExMan/p/9449954.html
Copyright © 2011-2022 走看看