我使用FBV计算时间增量(td)并将其传递到上下文中:
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()
然而,对于DetailView,我有CBV,并希望将same time_delta(td)作为附加上下文传递,但无法实现...我尝试了几种方法来传递
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()
有什么提示吗?
1条答案
按热度按时间ulydmbyx1#
可以使用
self.object
计算时间增量:这应该可以,因为Django把
get_object()
方法的结果赋给了self.object
变量。你可以在这里查看源代码。Django也直接将object传递到
get_context_data
,所以也可以从kwargs
获取: