我在这里上传多个文件,但是在添加时遇到了一些问题。外键不存储每个上传的文件。如何为每个选择的文件存储外键?
Cannot assign "<property object at 0x04667960>": "MoreImage.image_title" must be a "Gallery" instance.
模型
class Gallery(models.Model):
image_title = models.CharField(max_length=100, blank=True, null=True)
image_date = models.DateField(blank=True, null=True)
image = models.ImageField(upload_to='gallery', default='default.png')
class MoreImage(models.Model):
image_title = models.ForeignKey(Gallery, on_delete=models.CASCADE)
images = models.ImageField(upload_to='moreimage', default='default.png')
date = models.DateTimeField(auto_now_add=True)
观看次数
def add_more_image(request):
images = Gallery.objects.all().order_by('-date')
if request.method == 'POST':
form = MoreImageForm(request.POST or None, request.FILES or None)
if form.is_valid():
more = form.save(commit=False)
for file in request.FILES.getlist('image'):
MoreImage.objects.create(image_title=Gallery.pk, images=file)
#for field in request.FILES.keys():
#for form_file in request.FILES.getlist(field):
#img = MoreImage(image_title_id=Gallery.pk,images=form_file)
#img.save()
more.save()
messages.success(request, ' Images added.')
return redirect('admin:add_gallery')
MOreImage表单
class MoreImageForm(forms.ModelForm):
class Meta:
model = MoreImage
fields = '__all__'
答案 0 :(得分:1)
首先,您不应该调用 Gallery.pk
,因为它是类,因此不会返回任何内容。它应该类似于 gallary_instance.pk
而且我认为gallary_instance.pk
对您不起作用,因为您设置了 commit=False
,这会阻止将对象保存到数据库中。
尝试一下
def add_more_image(request):
images = Gallery.objects.all().order_by('-date')
if request.method == 'POST':
form = MoreImageForm(request.POST or None, request.FILES or None)
if form.is_valid():
more = form.save() # remove commit=False
for file in request.FILES.getlist('image'):
MoreImage.objects.create(image_title=more.image_title, images=file)
messages.success(request, ' Images added.')
return redirect('admin:add_gallery')