Context processors 写法及加载使用

第一:工程下创建context_processors.py模块

模块内写你自己的处理器函数:

如:


def custom_proc(request):
    "A context processor that provides 'app', 'user' and 'ip_address'."
    return {
        'app': 'My app',
        'user': request.user,
        'ip_address': request.META['REMOTE_ADDR']
    }
第二:打开settings,py,告诉项目使用你自定义的,在全局的settints。py中有些默认是自己加载的,比如user,i18n  debug


TEMPLATE_CONTEXT_PROCESSORS = (
   
    "项目名.context_processors.custom_proc",
)

第三:视图函数的一般写法

def view_2(request):
    return render_to_response('template2.html',
        {'message': 'I am the second view.'},
        context_instance=RequestContext(request)

第四:

模板里就可以使用

message  app user ip_address变量了

转载于:https://my.oschina.net/012345678/blog/129497

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
TEMPLATE_CONTEXT_PROCESSORS is a setting in Django that specifies a list of callables that are used to populate the context variable for all templates. These callables take the request object as an argument and return a dictionary of values that will be added to the context. By default, Django includes some context processors in this list, such as the auth context processor, which adds information about the currently logged-in user to the context. However, you can also add your own context processors to this list. To add a context processor, you need to define a callable that takes the request object as an argument and returns a dictionary. For example, you could define a context processor that adds the current date to the context: ```python from datetime import datetime def current_datetime(request): now = datetime.now() return {'current_datetime': now} ``` Then, you can add this context processor to the TEMPLATE_CONTEXT_PROCESSORS setting in your Django settings file: ```python TEMPLATE_CONTEXT_PROCESSORS = [ # Default context processors 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.debug', 'django.template.context_processors.request', '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', # Custom context processor 'myapp.context_processors.current_datetime', ] ``` Now, the `current_datetime` context processor will be called for every template and the `current_datetime` variable will be available in the template context.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值