简体   繁体   English

django-上下文处理器变量未更新

[英]django - context processor variables are not being updated

I have several variables within a navbar that are to be displayed on every single template, so I've made a custom context processor to handle the fetching of those variables. 我在导航栏中有几个要在每个模板上显示的变量,因此我制作了一个自定义上下文处理器来处理这些变量的提取。 Everything is working, except that when the data is changed in the database, the values of the context variables are not refreshed(for example it'll only get updated once I quit runserver and rerun). 一切正常,除了在数据库中更改数据时,上下文变量的值不会刷新(例如,仅当我退出runserver并重新运行时,上下文变量的值才会更新)。

Here's my basic pseudo code: 这是我的基本伪代码:

context_processor.py: context_processor.py:

foo = db.get('foo')
bar = db.get('bar')

def default(request):
    return {'foo': foo, 'bar': bar}

base.html: base.html:

{% block header %}
foo value is: {{ foo }}, bar value is {{ bar}}
{% endblock %}

{% block content %}
{% endblock %}

some_other_template.html: some_other_template.html:

{% extends "base.html" %}

{% block content %}
    ...blabla
{% endblock %}

Is there something I am missing or is this normal behavior? 我有什么想念的吗?还是这是正常现象? Have I used the wrong approach of using a context processor here? 我在这里使用上下文处理器是否使用了错误的方法?

When Django processes a template, it treats the html file as a string, and interpolates the values of variables in it prior to returning a result. Django处理模板时,会将html文件视为字符串,并在返回结果之前对其中的变量值进行插值。 This means that the values stay as they were in the time the template was rendered. 这意味着这些值将保持与渲染模板时相同的值。 There are many approaches to the thing you want to achieve, the simplest one is to take an AJAX approach and continuously poll for new values. 要实现目标的方法有很多,最简单的方法是采用AJAX方法并不断轮询新值。

That's because you're only reading them when the process starts instead of per request. 这是因为您只在流程启动时才读取它们,而不是根据每个请求读取它们。

You could either: 您可以:

a) retrieve them on every request (Eg. in the view, a context processor, etc..) a)根据每个请求(例如,视图中的上下文处理器等)检索它们

or 要么

b) Ensure the module variables you're storing them in are updated whenever they change (Eg. using a post_save signal). b)确保存储它们的模块变量在更改时(例如,使用post_save信号)进行更新。 This would, however, leave you open to unexpected behavior if you're ever running more than one process with one thread... 但是,如果您使用一个线程运行多个进程,这将使您容易遇到意外行为。

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

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