简体   繁体   English

Django 在不同的函数中使用相同的变量

[英]Django use the same variable in different functions

What I am trying to do is, fetching data from a third party app and show it on the page.我想要做的是,从第三方应用程序获取数据并将其显示在页面上。 I will get the data in get_context_data function and use the same data in get_initial method as well.我将在 get_context_data function 中get_initial get_context_data中使用相同的数据。 I could not manage to do that.我无法做到这一点。 Is there any way to do that?有没有办法做到这一点?

Example Code示例代码


class UpdateView(generic.FormView):
    template_name = 'test.html'
    form_class = myForm
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        MYVARIABLE = fetch_data_from_3rd_party_app()
        context["MYVARIABLE"] = MYVARIABLE
        return context

    def get_initial(self):
        initial = super().get_initial()

        # I want to assign MYVARIABLE.data to initial["data"] here.
        initial["data"] = MYVARIABLE

        return initial

There's a couple of options有几个选择

First there's the approach that the generic views from Django take and store the variable on self , assign it at some early point in the request (dispatch, get, post, etc) so that it's available to whoever needs it首先,来自 Django 的通用视图采用并将变量存储在self上的方法,在请求的早期分配它(调度、获取、发布等),以便任何需要它的人都可以使用它

class UpdateView(generic.FormView):

    def dispatch(self, request, *args, **kwargs):
        self.myvariable = fetch_data_from_3rd_party_app()
        return super().dispatch(request, *args, **kwargs)
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["MYVARIABLE"] = self.myvariable
        return context

    def get_initial(self):
        initial = super().get_initial()
        initial["data"] = self.myvariable
        return initial

I'm quite partial to using a cached property , assigning to self outside of __init__ feels slightly wrong to me (although there is nothing really wrong with it)我非常偏爱使用缓存属性,在__init__之外分配给self对我来说感觉有点不对劲(尽管它并没有什么真正的问题)

from django.utils.functional import cached_property

class UpdateView(generic.FormView):

    @cached_property
    def myvariable(self):
        return fetch_data_from_3rd_party_app()
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["MYVARIABLE"] = self.myvariable
        return context

    def get_initial(self):
        initial = super().get_initial()
        initial["data"] = self.myvariable
        return initial

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

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