在DetailView Django中传递附加数据

eagi6jfj  于 2022-12-20  发布在  Go
关注(0)|答案(1)|浏览(106)

我使用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()

有什么提示吗?

ulydmbyx

ulydmbyx1#

可以使用self.object计算时间增量:

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

这应该可以,因为Django把get_object()方法的结果赋给了self.object变量。你可以在这里查看源代码。
Django也直接将object传递到get_context_data,所以也可以从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

相关问题