我正在制作一款应用,要求用户上传一些文件。我想将所有文件存储在用户名文件夹中(可能稍后将其移到项目文件夹之外,但这是另一回事)
首先,我正在做一些测试,我采用了这个例子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)
我的views.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 debbuger:
>>> 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
我错过了什么?
非常感谢你。
答案 0 :(得分:1)
您正尝试将Document
对象保存为:
newdoc = Document(docfile = request.FILES['docfile'])
newdoc.save()
但您尚未为其设置owner
,get_upload_path
方法中instance.owner
未定义/设置instance.owner.username
并且newdoc = Document(docfile = request.FILES['docfile'])
newdoc.owner = request.user #set owner
newdoc.save()
将失败。
您可以将保存更改为:
DocumentForm
我不确定,你owner
是什么。但如果它还有newdoc
字段,那么您可以直接保存它,而不是单独创建...
if form.is_valid():
newdoc = form.save()
...
:
{{1}}