更改模型格式后文件上传无效

时间:2013-11-08 08:28:16

标签: python django file-upload django-models

我有一个类似于以下的模型类 -

class Document(models.Model):
    docfile = models.FileField(upload_to='documents/%Y/%M/%D')

一切正常,文件根据目录结构成功上传。

现在我不想上传这种格式的文件,只想上传一个文件夹中的所有文件,所以我改变了逻辑。

class Document(models.Model):
    docfile = models.FileField(upload_to='documents')

现在没有上传文件并抛出错误。也许我需要运行一些命令,但我不知道是什么??

请提出建议

EDIT1:

好的..我发现实际问题出在其他地方。

我有这样的观点 - (请忽略差距,但在实际代码中这很好)

def lists(request):

   // Problematic Code Start
   path = settings.MEDIA_URL + 'upload/location.txt' 
   f = open(path, 'w')
   myfile = File(f)
   myfile.write('Hello World')
   myfile.closed
   f.closed
   // Problematic Code ends


   # Handle file upload

   if request.method == 'POST':

       form = DocumentForm(request.POST, request.FILES)

       if form.is_valid():
           filename = Document(docfile = request.FILES['docfile'])
           filename.save()
           # Redirect to the document list after POST
       return HttpResponseRedirect(reverse('sdm:lists'))
       #return render_to_response(reverse('sdm:lists'))
   else:
       form = DocumentForm() # A empty, unbound form

       # Load documents for the list page
       documents = Document.objects.all()

       # Render list page with the documents and the form
       return render_to_response(
           'sdm/lists.html',
           {'documents': documents, 'form': form},
           context_instance=RequestContext(request)
       )

当我删除有问题的代码时,一切正常。 (忽略这个奇怪的代码的目的,实际的兴趣是更大的东西)

MEDIA_URL=/media/

这是错误:

 IOError at /sdm/lists

 [Errno 2] No such file or directory: '/media/upload/location.txt'

虽然文件存在且所有权限均为www-data:www-data 755

1 个答案:

答案 0 :(得分:1)

“有问题的”代码确实 - 无论谁写这个都应该找到另一份工作。这个代码错误的方式不止一种(使用MEDIA_URL而不是MEDIA_ROOT - 这是导致IOError的原因 - 并且严重误用Python的死简单文件对象)完全无用,看起来像某人偶然编程的遗留物。长话短说:只需删除它就可以了。