【发布时间】:2012-10-05 07:06:49
【问题描述】:
我正在制作一个应用程序,它需要用户上传一些文件。我想将所有文件存储在用户名文件夹中(并且可能稍后将其移出项目文件夹,但这是另一回事)
首先我在做一些测试,我以S.O: Need a minimal django file upload example为例。
它就是这样工作的,所以我转到下一步。
我检查了这些问题:
Django FileField with upload_to determined at runtime
Django store user image in model
我当前的models.py:
# models.py
from django.db import models
from django.contrib.auth.models import User
import os
def get_upload_path(instance, filename):
return os.path.join('docs', instance.owner.username, filename)
class Document(models.Model):
owner = models.ForeignKey(User)
docfile = models.FileField(upload_to=get_upload_path)
我的意见.py
@login_required
def list(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile = request.FILES['docfile'])
newdoc.save()
# Redirect to the document list after POST
return HttpResponseRedirect(reverse('myapp.views.list'))
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(
'myapp/list.html',
{'documents': documents, 'form': form},
context_instance=RequestContext(request)
)
所有接受的答案都会导致相同的解决方案。但是我遇到了 instance.owner 的错误:
django.contrib.auth.models.DoesNotExist
DoesNotExist
raise self.field.rel.to.DoesNotExist
使用 werkzeug 调试器:
>>> instance
<Document: Document object>
>>> instance.owner
Traceback (most recent call last):
File "<debugger>", line 1, in <module>
instance.owner
File "C:\Python27\lib\site-packages\django\db\models\fields\related.py", line 343, in __get__
raise self.field.rel.to.DoesNotExist
DoesNotExist
我错过了什么?
非常感谢您。
【问题讨论】:
标签: django django-models django-file-upload