Class Based Views - not updating context

Hello Everybody!

I am just making the transition to CBVs and have a beginner question that I couldn’t figure out using the docs. In I am taking the last db entry from a model and I am trying to calculate the number of seconds from it’s time stamp to now(). I am then throwing that value over to an html where I have some js continue to work on it. Here is my code:

class PositionView(TemplateView):

template_name = 'teachapp/position.html'

record = Finance.objects.latest('time_entry')

elapsed = ( - record.time_entry ).total_seconds()

extra_context = {'elapsed':elapsed}

I notice that it sends over the correct elapsed time the first time I visit the page but when I refresh it, the elapsed time does not change. It only updates after I runserver. I can make this work like a dream in an FBV but everyone keeps encouraging CBV that I am motivated to make it work.

I am certain that I am just misunderstanding classes.

Thanks in advance for your help!

In a class-based view, you add or modify behavior by overriding the functions defined in the class.

The class settings are evaluated once, when the class is loaded. That means they’re useful when you want to set a constant value. If you want to do something on every invocation, like calculating a value, that’s when the code needs to go into a function.

Yes, it’s tough at first to wrap your head around the CBVs.

You really should read all of Introduction to class-based views | Django documentation | Django and Built-in class-based generic views | Django documentation | Django, and then spend some time browsing CCBV and CBV diagrams.

1 Like