Reputation: 11
I have an expensive call in my view's get_context_data to calculate a field for the template. I would like to use this result in the view's get_initial_data to set the initial value of my_field but I cannot see how to access the context_data from within get_initial_data or how to pass it as a parameter.
def get_context_data( self, *args, **kwargs ):
context = super().get_context_data( **kwargs )
context['expensive_result'] = expensive_function()
return context
def get_initial( self, *args, **kwargs ):
initial = super().get_initial( **kwargs )
# Initialise my_field with expensive result calculated in get_context_data
initial['my_field'] = context['expensive_result'] # How to do this?
return initial
Upvotes: 1
Views: 515
Reputation: 66
get_initial
return self.initial.copy()
by docs
So, you can write:
def get_context_data( self, *args, **kwargs ):
expensive_value = expensive_function()
self.initial['my_field'] = expensive_value
context = super().get_context_data( **kwargs )
context['expensive_result'] = expensive_value
return context
You need to call it before get_context_data
'super' calling, because it calls get_initial
inside itself.
Or you can add field to your view class and write property for it:
class SomeView(CreateView):
_expensive_value = None
@propetry
def expensive_value(self):
if self._expensive_value is None:
self._expensive_value = expensive_function()
return self._expensive_value
def get_context_data( self, *args, **kwargs ):
context = super().get_context_data( **kwargs )
context['expensive_result'] = self.expensive_value
return context
def get_initial( self, *args, **kwargs ):
initial = super().get_initial( **kwargs )
initial['my_field'] = self.expensive_value
return initial
And using this propetry inside both get_context_data
and get_initial
will called expensive_function
just one time.
Upvotes: 1