Handling Image Uploads in Django
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()
开发者_Python百科 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?
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
精彩评论