2

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

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks mate, I really liked this cached_property

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.