如何向用户显示仅可用的模型字段?

时间:2018-06-12 01:19:55

标签: python django-models django-forms django-views django-queryset

我有两种车型和预订。如果汽车被预订,那么汽车在预订模型中是ForeignKey字段,然后在汽车列表中它仍然显示可用。我在汽车模型default=True中有is_available_car模型字段。 如果汽车被预订,那么它将无法显示,直到它没有预订。 我在车里预订表格是外键,用户预订车后仍显示车。 请帮帮我。谢谢。

模型

class 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})

观看.py

class BookingView(FormView):
 template_name = 'buggy_app/booking.html'
 form_class = BookingForm
 models = Booking
 def form_valid(self, form):
    form.save()
    return super(BookingView, self).form_valid(form)

 success_url = reverse_lazy('index')

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 initial

 class CarListView(ListView):
  context_object_name = 'cars'
  model = models.Car

def get_queryset(self):
    qs = super(CarListView, self).get_queryset()
    qs = qs.filter(is_available_car=True)
    return qs

1 个答案:

答案 0 :(得分:2)

在您收到预订请求的视图中,获取views.py的标识符并更改其is_available_car属性:

class BookingView(FormView): ... def form_valid(self, form): car_id = self.request.GET.get('car', '') car = Car.objects.get(id=car_id) car.is_available_car = False car.save() form.save() return super(BookingView, self).form_valid(form)

is_available_car=False

在汽车列表中,您应该过滤具有{{1}}

的汽车