使用django-imagekit在视图中保存照片时出现问题

时间:2010-02-03 09:37:39

标签: django django-forms django-imagekit

我在我的一个观点中使用此代码:

    if request.method == 'POST':
      vehicle = VehicleForm(request.POST or None)
      photos = PhotosFormSet(request.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))

但是当我尝试提交表单时,我收到错误:'VehicleForm' object has no attribute 'pk'

我已将PhotosFormSet声明为:

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

然后我的Photo课程如下:

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'

1 个答案:

答案 0 :(得分:0)

这是你的问题:

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

vehicle这里是Form,而不是Vehicle对象。 .save()返回一个新的Vehicle,但是你没有将它设置为一个变量,所以它丢失了。然后,您将表单而不是新对象传递给表单集。

相反,只需这样做:

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