Wessi
Wessi

Reputation: 1822

Django form - key error

I have a form implemented in a ListView. The form is used for editing existing items. However I get a key error when i try to submit the form: 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

This is the main code:

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')

What causes this key error?

Thanks!

Upvotes: 0

Views: 516

Answers (1)

Brobin
Brobin

Reputation: 3326

id is not in your kwargs, that is causing the KeyError. In fact, you don't need to load the car like that. Your method can be simplified to this:

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')

Upvotes: 1

Related Questions