I have FBV where I am calculating time delta (td) and passing it in my context:
def update_moc(request, pk):
moc = get_object_or_404(Moc, pk=pk)
today = datetime.date.today()
time = moc.initiation_date
time_delta = today - time
td=str(time_delta)
initiator = moc.initiator
status = moc.moc_status
coordinator = moc.coordinators.filter(coordinator_name=request.user)
if request.user.is_superuser or (initiator == request.user or coordinator) and status == 'draft':
form = MocUpdateForm(request.POST or None, instance=moc)
today = datetime.date.today()
time = moc.initiation_date
time_delta = today - time
td=str(time_delta)
if form.is_valid():
moc.initiator = request.user
form.save()
return HttpResponseRedirect(reverse('moc_content_detail', kwargs={'pk': pk}))
else:
return render(request, 'moc/moc_content.html', context={'moc':moc, 'form':form, 'td': td})
else:
raise Http404()
However for DetailView I am having CBV and want to pass same time_delta (td) as additional context, but failing how I can do it... I tried few approaches to pass
class MocDetailView(LoginRequiredMixin, DetailView):
model = Moc
template_name = 'moc/moc_detail.html'
def get_context_data(self, *args, **kwargs):
context = super(MocDetailView, self).get_context_data(*args, **kwargs)
context['td'] = # This is where I need help
def get_object(self, queryset=None):
obj = super(MocDetailView, self).get_object(queryset=queryset)
confidential = obj.confidential
initiator = obj.initiator
.....
if self.request.user.is_superuser or initiator == self.request.user or verifier or coordinator or reviewer or approver or preimplement or authorizer or postimplement or closer and confidential == True:
return obj
elif not confidential:
return obj
else:
raise Http404()
Any hints please?
CodePudding user response:
You can use self.object
to calculate timedelta:
def get_context_data(self, *args, **kwargs):
context = super(MocDetailView, self).get_context_data(*args, **kwargs)
time = self.object.initiation_date
today = datetime.date.today()
time_delta = today - time
td=str(time_delta)
context['td'] = td
return context
This should work because Django assign the result of get_object()
method to self.object
variable. You can check the source code here.
Also Django passes object into get_context_data
directly, so it's also possible to get it from kwargs
:
def get_context_data(self, *args, **kwargs):
context = super(MocDetailView, self).get_context_data(*args, **kwargs)
time = kwargs['object'].initiation_date
# rest of the code