我有两个模型,Car
和Booking
。 Car
是ForeignKey
模型中的Booking
字段。如果预订了Car
,它仍然显示在Car
列表中。
我将is_available_car
模型中的Car
模型字段设置为default=True
。如果Car
已预订,则直到取消预订它才会显示。我有一个预订表格,如果预订了Car
,则用户无法预订它,并且它没有显示在CarListView
请帮帮我。谢谢。
models.py
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})
views.py
class 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 initial
class CarListView(ListView):
context_object_name = 'cars'
model = Car
def get_queryset(self):
qs = super(CarListView, self).get_queryset()
qs = qs.filter(is_available_car=True)
return qs
答案 0 :(得分:0)
我借助@seuling
找到了解决方案 class BookingView(FormView):
template_name = 'buggy_app/booking.html'
form_class = BookingForm
models = Booking
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)
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)