多个图像未保存到其外键对象

时间:2016-03-15 02:17:12

标签: python django django-views django-1.9

我使用前端视图库创建了一个表单,用户可以上传多个图像。我可以开发它但图像不会保存到相关的租金中。为此,我必须从admnin手动分配租金。

mannually assigned from admin(this is what i am wanting but not through admin.It should be automatically populate when uploaded)

But images are saved like this. They are not associated with its rent when they are uploaded

Models.py

class Rental(models.Model):
    name = models.CharField(_("Owner's Name"),max_length=255, blank=True,null=True)
    email = models.CharField(max_length=120,blank=True,null=True)

class GalleryImage(models.Model):
    rental = models.ForeignKey('Rental',on_delete=models.CASCADE,blank=True,null=True,
                                verbose_name=_('Rental'), related_name="gallery")
    image = models.ImageField(blank=True,upload_to='upload/',null=True)

views.py用于图片上传

class UploadImage(View):
    model = Rental
    def post(self,request,*args,**kwargs):
        if request.FILES:
            for file in request.FILES.getlist('image'):
                print('file',file)
                # rental = request.POST.get('rental', False)
                # print('rental is', rental)
                image = GalleryImage.objects.create(image=file)
                image.save()
        return HttpResponseRedirect('/')

class AddView(TemplateView): // upload form is in add.html template
    template_name = 'rentals/add.html'

urls.py

url(r'^add/$', AddView.as_view(), name="add"),
url(r'^upload/image/$', UploadImage.as_view(), name="uploadImage"),

addrent.js(用于多张图片上传的ajax代码)

var image = [];
image = new FormData(files);
$.each(files,function(i,file){
  image.append('image',file);
});
$.ajax({
    url:"/upload/image/",
    data:image,
    contentType:false,
    processData:false,
    type:'POST',
    mimeType: "multipart/form-data",
    success: function(data) {
      console.log('success');
    }
});
}

我需要做些什么来将多个图像保存到与第一张图像相关的租借实例?

1 个答案:

答案 0 :(得分:1)

您需要以某种方式(在URL路径或URL GET参数中)发送租借对象的ID。然后在视图中,您需要获取对象,并在创建GalleryImage对象时将其作为参数传递。

此外,您不需要在image.save()之后致电objects.create()。它已经存在于数据库中。