开发者

Problem saving photos in a view using django-imagekit

开发者 https://www.devze.com 2022-12-18 18:36 出处:网络
I\'m using this code in one of my views: if request.method == \'POST\': vehicle = VehicleForm(request.POST or None)

I'm using this code in one of my views:

    if request.method == 'POST':
      vehicle = VehicleForm(request.POST or None)
      photos = PhotosFormSet(reque开发者_如何学Cst.POST or None)
      if vehicle.is_valid():
        vehicle.save()
        photos = PhotosFormSet(request.POST, instance=vehicle)
        photos.save()
        return HttpResponseRedirect('/vehicles/')
    else:
      vehicle = VehicleForm()
      photos = PhotosFormSet(instance=Vehicle())

    return render_to_response('vehicles/vehicles-add-edit.html', 
           {'vehicle': vehicle, 'photos': photos}, 
           context_instance=RequestContext(request))

But I get an error: 'VehicleForm' object has no attribute 'pk' when I try to submit the form.

I've declared PhotosFormSet as:

from django.contrib.contenttypes.generic import generic_inlineformset_factory
PhotosFormSet = generic_inlineformset_factory(Photo, extra=10)

Then my Photo class is as follows:

class Photo(ImageModel):
  name = models.CharField(max_length=100)
  original_image = models.ImageField(upload_to='photos')
  num_views = models.PositiveIntegerField(editable=False, default=0)
  position = models.ForeignKey(PhotoPosition)
  content_type = models.ForeignKey(ContentType)
  object_id = models.PositiveIntegerField()
  content_object = generic.GenericForeignKey('content_type', 'object_id')

  class IKOptions:
    spec_module = 'specs'
    cache_dir = 'photos'
    image_field = 'original_image'
    save_count_as = 'num_views'


Here's your problem:

vehicle.save()
photos = PhotosFormSet(request.POST, instance=vehicle)

vehicle here is the Form, not the Vehicle object. .save() returns a new Vehicle, but you don't set it to a variable, so it's lost. You're then passing the form, not the new object, to the formset.

Instead, just do this:

new_vehicle = vehicle.save()
photos = PhotosFormSet(request.POST, instance=new_vehicle)
0

精彩评论

暂无评论...
验证码 换一张
取 消