[Answered ]-Access Django context data in get_initial

1👍

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.

👤lmaxyz

Leave a comment