在Django CBV中显示之前如何检查对象状态

时间:2019-04-12 10:09:27

标签: python django

我想在视图中检查对象的状态。如果为True,则什么都不会改变,但是如果状态不是True,我想将用户重定向到另一个页面。

这是我的观点:

final List<String> names = copyData.get(i).fieldNames;
  final List<Object> values = copyData.get(i).values;

我在产品模型中有一个状态字段,如下所示:

class ProductDetailView(LoginRequiredMixin, MultiSlugMixin, DetailView):
    model = Product

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        product_name = self.object.title
        category_commission = self.object.category.commission
        data = Stocks.objects.filter(product__title__icontains=product_name).order_by('price')
        context['category_commission'] = category_commission
        context['stocks'] = data

        return context

我想实现以下目标:

status = models.BooleanField(default=False)

1 个答案:

答案 0 :(得分:2)

当状态不是import cv2 import time FPS = 0 cap = cv2.VideoCapture(0) fourcc = cv2.VideoWriter_fourcc(*'MJPG') if(not cap.isOpened()): exit() cap.set(cv2.CAP_PROP_FOURCC, fourcc); cap.open(cv2.CAP_ANY); cap.set(cv2.CAP_PROP_CONVERT_RGB, 0); cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280) cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720) cap.set(cv2.CAP_PROP_FPS, 60) last = time.time() for i in range(0,100): before = time.time() rval, frame = cap.read() now = time.time() print("cap.read() took: " + str(now - before)) if(now - last >= 1): print(FPS) last = now FPS = 0 else: FPS += 1 cap.release() 时,只需覆盖True即可很容易地显示404页面

get_queryset.

但是,这并不是您要求的行为。如果要重定向,则必须覆盖def get_queryset(self): return = super(ProductDetailView, self).get_queryset().filter(status=True) get,例如:

dispatch

这不是理想的,因为您正在从BaseDetailView.get()方法复制代码,但是它使代码流程清晰明了。您可以在class ProductDetailView(LoginRequiredMixin, MultiSlugMixin, DetailView): ... def get(self, request, *args, **kwargs): self.object = self.get_object() if not self.object.status: return redirect('productlistpage') context = self.get_context_data(object=self.object) return self.render_to_response(context) 方法中调用super(),但是最终您会调用get()两次,或者在重定向之前不必要地渲染了模板。