簡體   English   中英

Django 在不同的函數中使用相同的變量

[英]Django use the same variable in different functions

我想要做的是,從第三方應用程序獲取數據並將其顯示在頁面上。 我將在 get_context_data function 中get_initial get_context_data中使用相同的數據。 我無法做到這一點。 有沒有辦法做到這一點?

示例代碼


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

有幾個選擇

首先,來自 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

我非常偏愛使用緩存屬性,在__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