zoukankan      html  css  js  c++  java
  • django 上下文渲染器

    需求介绍:

    所有页面需要检测用户是否登陆,并渲染 登录|注册 或是用户名。

    动手写个上下文渲染器

    1.项目路径

    zqxt
    ├── blog
    │   ├── __init__.py
    │   ├── admin.py
    │   ├── migrations
    │   │   └── __init__.py
    │   ├── models.py
    │   ├── tests.py
    │   └── views.py
    ├── manage.py
    └── zqxt
        ├── __init__.py
        ├── settings.py
        ├── urls.py
        └── wsgi.py
    

    2.在 zqxt/zqxt/ 这个目录下(与settings.py 在一起)新建一个 context_processor.py

    from django.conf import settings as original_settings
     
     
    def settings(request):
        return {'settings': original_settings}
     
     
    def ip_address(request):
        return {'ip_address': request.META['REMOTE_ADDR']}

    3.我们把新建的两个 上下文渲染器 加入到 settings.py 中

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
     
                    'zqxt.context_processor.settings',
                    'zqxt.context_processor.ip_address',
                ],
            },
        },
    ]
    

      

    我们仅需在模板中使用这些context中的变量即可。我们在view中的context并不会被影响到,但使用上下文渲染器将会导致缓存优化困难的问题。

  • 相关阅读:
    CentOS 6.5、6.7 设置静态 ip 教程
    Nagios
    zabbix
    xml 的 <![CDATA["URL"]]>
    Don't make a promise when you are in Joy. Don't reply when you are Sad.Don't take decisions when you are Angry.Think Twice.Act Wise.
    DNS-2
    APM
    Time crumbles things; everything grows old under the power of Time and is forgotten through the lapse of Time
    CentOS 7 配置静态 ip
    AOP
  • 原文地址:https://www.cnblogs.com/zenan/p/8783165.html
Copyright © 2011-2022 走看看