Django表单 - 关键错误

时间:2016-12-14 21:14:57

标签: django django-forms

我有一个在ListView中实现的表单。该表单用于编辑现有项目。但是,当我尝试提交表单时,我收到了一个关键错误: File "C:\Users\John\Desktop\website\app\views.py", line 124, in form_valid id = self.kwargs['id'] KeyError: 'id' [14/Dec/2016 21:42:09] "POST /car/ HTTP/1.1" 500 99346

这是主要代码:

class CarListFormView(FormView):
    form_class = CarListForm

    def form_valid(self, form):
        id = self.kwargs['id']
        obj = Car.objects.get(pk=id)
        form = CarListForm(instance=obj)
        car = form.save(commit=False)

        if self.request.user.is_staff:
            car.agency = Agency.objects.get(agency_id=9000)
        else:
            car.agency = self.request.user.agency
        car.save()
        return redirect('car_list')

导致此键错误的原因是什么?

谢谢!

1 个答案:

答案 0 :(得分:1)

kwargs不在from django.views.generic import UpdateView class CarListFormView(UpdateView): model = Car form_class = CarListForm template_name = 'something/car_form.html' def form_valid(self, form): car = form.save(commit=False) if self.request.user.is_staff: car.agency = Agency.objects.get(agency_id=9000) else: car.agency = self.request.user.agency car.save() return redirect('car_list') 中,导致KeyError。事实上,你不需要像那样装车。您的方法可以简化为:

Trim