我有两个模型, Car和Booking。ACar是模型中的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
相关分类