为了账号安全,请及时绑定邮箱和手机立即绑定

Django如何仅在CBV列表视图中显示可用项目?

Django如何仅在CBV列表视图中显示可用项目?

智慧大石 2021-03-30 13:10:58
我有两个模型, Car和Booking。ACar是模型中的ForeignKey字段Booking。如果Car已预订,它仍显示在Car列表中。我在is_available_car模型字段中将模型字段Car设置为default=True。如果Car已预订,则在未预订之前不会显示。我有一个预订表格,如果Car已预订,用户将无法预订,并且不会显示在CarListView请帮帮我。谢谢你。models.pyclass Booking(models.Model):    booking_name = models.CharField(max_length=240, null=False)    customer_name = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='book_customers' )    book_car = models.ForeignKey(Car, on_delete=models.CASCADE, related_name='book_car')    booking_start_date = models.DateTimeField(auto_now_add=True, blank=False)    booking_end_date = models.DateTimeField(blank=True, null=True)    rental_price = models.IntegerField(blank=False, null=False)    times_pick = models.TimeField(blank=True)    is_approved = models.BooleanField(default=False)    def __str__(self):        return self.booking_name    def get_absolute_url(self):        return reverse("buggy_app:detail",kwargs={'pk':self.pk})views.pyclass BookingView(FormView):    template_name = 'buggy_app/booking.html'    form_class = BookingForm    model = Booking     success_url = reverse_lazy('index')    def form_valid(self, form):        form.save()        return super(BookingView, self).form_valid(form)    def get_context_data(self, **kwargs):        # kwargs['car'] is the car booking now!        try:            kwargs['car'] = Car.objects.get(id=self.request.GET.get('car', ''))        except (Car.DoesNotExist, ValueError):            kwargs['car'] = None            return super(BookingView, self).get_context_data(**kwargs)    def get_initial(self):        initial = super(BookingView, self).get_initial()        if 'car' in self.request.GET:            try:                initial['book_car'] = Car.objects.get(id=self.request.GET['car'])            except (Car.DoesNotExist, ValueError):                pass                return initialclass CarListView(ListView):    context_object_name = 'cars'    model = Car
查看完整描述

1 回答

  • 1 回答
  • 0 关注
  • 118 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信