gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 16:49:27 25 4
gpt4 key购买 nike

我使用前端 View 库创建了一个表单,用户可以在其中上传多个图像。我可以冲洗它,但图像不会保存到其相关的租金中。为此,我必须从管理员那里手动分配租金。

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)

用于图片上传的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');
}
});
}

我必须做什么才能将多个图像保存到其关联的租赁实例(如第一个图像)?

最佳答案

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

此外,您不需要在 objects.create() 之后调用 image.save()。它已经在数据库中了。

关于python - 多个图像未保存到其外键对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36001532/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com