简体   繁体   中英

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. 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

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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