2

ユーザーがいくつかのファイルをアップロードする必要があるアプリを作成しています。すべてのファイルをユーザー名フォルダーに保存したい(そして、後でプロジェクトフォルダーの外に移動することもできますが、それは別のことです)

最初にいくつかのテストを行っています。この例を取り上げました。SO:最小限のdjangoファイルのアップロード例が必要です

そのように機能したので、次のステップに進みました。

私はこの質問をチェックしました:

実行時にupload_toが決定されたDjangoFileField

Djangoの動的ファイルパス

Djangoはユーザー画像をモデルに保存します

私の現在の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

私は何が欠けていますか?

事前にどうもありがとうございました。

4

1 に答える 1

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()
...
于 2012-10-15T10:24:44.387 に答える