我正在制作一个应用程序,它需要用户上传一些文件。我想将所有文件存储在用户名文件夹中(并且可能稍后将其移出项目文件夹,但这是另一回事)
首先我在做一些测试,我拿了这个例子,所以:需要一个最小的 django 文件上传示例。
它就像那样工作,所以我进入下一步。
我检查了这个问题:
Django FileField with upload_to 在运行时确定
我当前的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
我错过了什么?
非常感谢您提前。