简体   繁体   English

Django-视图中的上下文处理器?

[英]Django - context processors in the view?

Context processors in Django usually allow for a variable to be accessed by all templates. Django中的上下文处理器通常允许所有模板访问变量。 How do I access this variable in the views.py (backend) code? 如何在views.py(后端)代码中访问此变量?

Here is what I have tried: 这是我尝试过的:

def index(request):
    request_context = RequestContext(request)
    center =  request_context.get("center")

But I get "none" for the center variable. 但是我的中心变量“无”。

And in the context processor code: 并在上下文处理器代码中:

def center(request):
return {'center': '123'}

I have added the context processor's "center" function to the context processor list in settings. 我已将上下文处理器的“中心”功能添加到设置中的上下文处理器列表中。

Use decorators instead of context_processors . 使用decorators而不是context_processors It will be really very simple for you. 这对您来说真的非常简单。 In views.py use @csrf_exempt before function from which you want to take a variable and use {% csrf_token %} on the end of a line in the template where you want to use that variable. views.py在要从中获取变量的函数前使用@csrf_exempt ,并在要使用该变量的模板的行尾使用{% csrf_token %}
Official documentation on csrf decorators 有关CSRF装饰器的官方文档

If you need to see an example then check out this . 如果您需要看到一个例子,然后检查了这个 Here in template/add_comment.html and views.py is using decorators. 这里在template / add_comment.html和views.py中使用装饰器。

NOTE :- you need to import csrf_exempt in views.py before using it like:- 注意 :-您需要先在views.py中导入csrf_exempt,然后才能使用它:-
from django.views.decorators.csrf import csrf_exempt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM