Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python django变量可用于所有视图_Python_Django_Django Views - Fatal编程技术网

Python django变量可用于所有视图

Python django变量可用于所有视图,python,django,django-views,Python,Django,Django Views,使用上下文处理器,可以很容易地定义一个可调用函数,该函数将生成所有模板都可用的变量。是否有类似的技术使变量可用于所有视图?这有可能吗?也许需要一些解决办法 Django:2.2 Python:3.5.3 .您可以尝试将变量发送到每个基于类的视图的上下文中,方法是拥有一个父类并从该父类继承所有视图 class MyMixin(object): def get_context_data(self, **kwargs): context = super(MyMixin, sel

使用上下文处理器,可以很容易地定义一个可调用函数,该函数将生成所有模板都可用的变量。是否有类似的技术使变量可用于所有视图?这有可能吗?也许需要一些解决办法

Django:2.2 Python:3.5.3


.

您可以尝试将变量发送到每个基于类的视图的上下文中,方法是拥有一个父类并从该父类继承所有视图

class MyMixin(object):
    def get_context_data(self, **kwargs):
        context = super(MyMixin, self).get_context_data(**kwargs)
        myvariable = "myvariable"
        context['variable'] = myvariable
        return context

# then you can inherit any kind of view from this class.

class MyListView(MyMixin, ListView):
    def get_context_data(self, **kwargs):
        context = super(MyListView, self).get_context_data(**kwargs)
        ...  #additions to context(if any)
        return context
或者,如果您使用的是基于函数的视图,则可以使用单独的函数来更新上下文
dict

def update_context(context):  #you can pass the request object here if you need
    myvariable = "myvariable"
    context.update({"myvariable": myvariable})
    return context

def myrequest(request):
    ...
    context = {
        'blah': blah
    }
    new_context = update_context(context)
    return render(request, "app/index.html", new_context)

您可能想要实现一个自定义中间件


这使您可以为每个请求执行自定义代码,并将结果附加到
请求
对象,然后可以在您的视图中访问。

使用您想要的变量创建一个类,并在每个视图类中继承该变量。全局变量呢?很遗憾,在这个项目中没有基于类的视图。很遗憾,目前在这个项目中没有基于类的视图。这非常好,谢谢。我不认为编写一个简单的中间件这么容易。