【问题标题】:Django upload file per user relationship errorDjango按用户关系上传文件错误
【发布时间】:2012-10-05 07:06:49
【问题描述】:

我正在制作一个应用程序,它需要用户上传一些文件。我想将所有文件存储在用户名文件夹中(并且可能稍后将其移出项目文件夹,但这是另一回事)

首先我在做一些测试,我以S.O: Need a minimal django file upload example为例。

它就是这样工作的,所以我转到下一步。

我检查了这些问题:

Django FileField with upload_to determined at runtime

Dynamic File Path in Django

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


    【解决方案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()
    ...
    

    【讨论】:

    • 天哪,这么愚蠢的错误,我没看到。它现在似乎起作用了。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-23
    • 2017-04-28
    • 1970-01-01
    • 1970-01-01
    • 2020-10-13
    • 2014-12-04
    • 2013-03-13
    相关资源
    最近更新 更多