我的所有对象newmedia都以相同名称保存。 我该如何解决这个问题?
#view.py
if request.method == 'POST':
formset = MediaFormSet(request.POST, request.FILES)
if formset.is_valid():
Page_key = Page.objects.get(pk=1)
slide = SlideshowComponent(page=Page_key, order=0, label="slideshow", x=0, y=0, width=0, height=0, viewport_type="simle_page", keywords="slideshow")
slide.save()
for filename, file in request.FILES.iteritems():
name = request.FILES[filename].name
for form in formset.forms:
file_type = file.content_type
if file_type == "image/png" or file_type == "image/jpeg" or file_type == "image/gif":
newmedia = formset.save(commit=False)
newmedia.filename = name
newmedia.content_type = "photos"
newmedia.save()
答案 0 :(得分:1)
我猜你省略了一个表格:
for filename, file in request.FILES.iteritems():
name = request.FILES[filename].name
for form in formset.forms:
file_type = file.content_type
if file_type == "image/png" or file_type == "image/jpeg" or file_type == "image/gif":
newmedia = formset.save(commit=False)
newmedia.filename = name
newmedia.content_type = "photos"
newmedia.save()
否则它始终保留您处理的最后一个文件的名称。
编辑:事实上,我想这不是你想要的。您应该跟踪已经处理的formset.forms,然后指定与尚未处理的formset.forms一起的名称。答案 1 :(得分:0)
相反,我有2个,我只做一个。
for file in request.FILES.getlist('form-0-source'):
file_type = file.content_type
if file_type == "image/png" or file_type == "image/jpeg" or file_type == "image/gif":
name= file.name.split('.')[0]
newmedia = Media(source=file, filename=name, content_type = "photos", created='03/25/12')
newmedia.save()
image2 = ImageComponent(page=Page_key, order=0, label="imagem", x=0, y=0, width=0, height=0, viewport_type="simle_page", keywords="imagem", media=newmedia, is_slideshow='true')
image2.save()
slide.image.add(image2)
else:
return render_to_response('revista_digital/error.html', context_instance=RequestContext(request))