views:

65

answers:

1

I have this view for my form:

if request.method == 'POST':
    vehicle = VehicleForm(request.POST or None)
    photos = PhotosFormSet(request.POST or None)
    if vehicle.is_valid() and photos.is_valid():
        new = vehicle.save()
        photos = PhotosFormSet(request.POST, instance=new)
        photos.save()
        return HttpResponseRedirect('/vehicles/')
else:
    prefix = "09-"
    queryset = Vehicle.objects.all().order_by("stock_number")
    if queryset == None:
        last_rec = queryset.reverse()[0]
        a = str(last_rec.stock_number)
        b = int(a[-3:])+1
        next = prefix+str(b)
    else:
        next = prefix+"001"
    vehicle = VehicleForm(initial={'stock_number': next})
    photos = PhotosFormSet(instance=Vehicle())

However when I try to save the record, the image field in PhotosFormset gives an error saying This field is required.

PhotosFormset is declared as PhotosFormSet = generic_inlineformset_factory(Photo, extra=5)

What am I missing here?

+3  A: 

You don't appear to be binding uploaded files to your formset. You need to pass in request.FILES as well as request.POST:

photos = PhotosFormSet(request.POST, request.FILES, instance=new)

More info in the Django docs

Harold
I was just going over than bit of the docs a few minutes back and saw the same bit. Thanks
Stephen
I also needed enctype="multipart/form-data" in my <form> element in addition to request.FILES
Stephen