如何从详细视图传递到形成外键字段?

时间:2018-06-08 00:19:30

标签: python django django-class-based-views

我有预订表格的汽车和btn预订href的详细视图。我想通过那辆细节正在展示的那辆车。而不是我总是从foreignkey下拉车选择。

1 个答案:

答案 0 :(得分:0)

车载细节视图中的

<a href="{% url 'car_booking' %}?car={{ car.id }}">Booking Now</a>

然后考虑到汽车预订:

class BookingView(FormView):
    template_name = 'car/booking.html'
    form_class = BookingForm

    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)

    # if you still want to keep select car in form,and auto select this car do as:
    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

url可能会喜欢:

path('booking/', BookingView.as_view(), name='car_booking'),