Question

I'm making an app, which requires users to upload some files. I want to store all files in a username folder (and possibly, later move it outside the project folder, but that's other thing)

First I'm doing some tests, I took this example S.O: Need a minimal django file upload example.

It worked just like that, so I moved to next step.

I checked this questions:

Django FileField with upload_to determined at runtime

Dynamic File Path in Django

Django store user image in model

My current 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)

My 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)
    )

All accepted answers, lead to the same solution. But I'm getting an error with instance.owner:

django.contrib.auth.models.DoesNotExist
DoesNotExist
raise self.field.rel.to.DoesNotExist

Using 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

What am I missing?

Thank you very much in advance.

Was it helpful?

Solution

You are trying to save a Document object as :

newdoc = Document(docfile = request.FILES['docfile'])
newdoc.save()

But you haven't set owner for it, you in get_upload_path method instance.owner is not defined/set and instance.owner.username will fail.

Either you change your save as:

newdoc = Document(docfile = request.FILES['docfile'])
newdoc.owner = request.user #set owner
newdoc.save()

I'm not sure, what is your DocumentForm is. But if it also has owner field then you can directly save it instead of creating newdoc separately as:

...
if form.is_valid():
    newdoc = form.save()
...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top