我正在 django 为 uber 司机开发一个汽车租赁网站,从详细视图我需要司机能够选择他们的租赁期限,其他信息将自动填写到我的views.py的表格中,我能够为了通过request.user获取司机,我还需要租赁汽车的PK。在这里搜索时,我尝试了这里人们的各种建议,但我不断收到一个又一个错误......
使用 self.kwargs['pk']结果ValueError at /car/offer/4/ Cannot assign "4": "CarRent.car" must be a "Car" instance.
然后我尝试使用 form.car = Car.objects.get(pk= self.kwargs.get('pk'))它的结果AttributeError at /car/offer/4/ 'CarRent' object has no attribute 'is_valid'
有人可以告诉我如何获取 CarRent 模型中保存的汽车实例吗?任何帮助将不胜感激。谢谢
下面是我的代码(减少到相关位)
models.py
class Car(models.Model):
car_owner = models.ForeignKey(User, related_name='car_owner', on_delete=models.CASCADE)
class CarRent(models.Model):
car = models.ForeignKey(Car, related_name='rented_car', on_delete=models.CASCADE)
driver = models.ForeignKey(User, related_name='driver_renting', on_delete=models.CASCADE)
rented_weeks = models.BigIntegerField(default=1, choices=WEEK_CHOICES)
forms.py
class RentForm(forms.ModelForm):
class Meta:
model = CarRent
fields = ['rented_weeks']
我只显示租用的周数,因为这是我需要用户提供的唯一信息。
views.py
class CarView(FormMixin, DetailView):
model = Car
form_class = RentForm
def get_success_url(self):
return reverse('car-details', kwargs={'pk': self.object.pk})
def post(self, request, *args, **kwargs):
if not request.user.is_authenticated:
return HttpResponseForbidden()
self.object = self.get_object()
form = self.get_form()
form = form.save(commit=False)
form.car = self.kwargs['pk']
form.driver = request.user
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
def form_valid(self, form):
form.save()
return super().form_valid(form)
有只小跳蛙
相关分类