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

2024-04-25 17:39:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经创建了一个表单使用前端视图库,用户可以上传多个图像。我可以开发它,但图像没有保存到它的相关租金。为此,我必须手动分配租金从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

型号.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)

视图.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'

网址.py

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

添加租金.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');
    }
});
}

我要做什么才能像第一个图像一样将多个图像保存到它们关联的租用实例?你知道吗


Tags: name图像imageaddtruemodelsrequestnull
1条回答
网友
1楼 · 发布于 2024-04-25 17:39:36

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

另外,您不需要在objects.create()之后调用image.save()。它已经在数据库里了。你知道吗

相关问题 更多 >