2016-03-15 40 views
1

我已经创建了一个使用前端视图库的窗体,用户可以上传多个图像。我可以开发它,但图像不会保存到相关的租金。为此,我必须从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'); 
    } 
}); 
} 

我有什么做的多张图像保存到他们的相关租金情况,如第一图片 ?

+0

我不明白你创建对象的方式,你使用“创建”,为什么不用实例化所有参数的对象,而只是保存它?除此之外,出租的参数并没有明确地传递给服务器(就我所见,您发布的代码而言)。你能展示模板吗? – softwareplay

回答

1

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

你也不需要在objects.create()之后拨打image.save()。它已经在数据库中。