0

我所有的对象 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()
4

2 回答 2

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 一起出现的名称。

于 2012-06-13T11:08:55.687 回答
0

相反,我有 2 个 for,我只用一个 for 做所有事情。

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))
于 2012-06-14T11:40:46.673 回答