0

I want to create user specific folders for files uploaded by users. This is 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('upload.views.list'))
    else:
        form = DocumentForm() # An 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(
        'upload/list.html',
        {'documents': documents, 'form': form},
        context_instance=RequestContext(request)
    )

This is my models.py:

class Document(models.Model):
    docfile = models.FileField(upload_to='uploads/%Y.%m.%d')

My idea is this. Instead of naming it uploads/%Y.%m.%d I stick the username somewhere in there. Is there a way to do that?

1
  • pass the current user after the form.is_valid(): user = request.user And pass it as an argument to your model.
    – petkostas
    Jun 10, 2014 at 17:47

1 Answer 1

2

I do something like that in my models.py:

def _upload_path(instance,filename):
    return instance.get_upload_path(filename)

class Document(models.Model):
    docfile = models.FileField(upload_to=_upload_path)
    user = models.ForeignKey('auth.User')

    def get_upload_path(self,filename):
        return "static/uploads/"+str(self.user.id)+"/"+filename
7
  • Thanks for the reply but I must be doing something wrong. I get " 'Document' object has no attribute 'user' "
    – KSHMR
    Jun 10, 2014 at 16:56
  • This is because your Document model doesn't have a user field.
    – cor
    Jun 10, 2014 at 17:00
  • So I must first define the user object with an id?
    – KSHMR
    Jun 10, 2014 at 17:08
  • Sorry I was not clear enough, this returns an error: " no such column: upload_document.user_id "
    – KSHMR
    Jun 10, 2014 at 17:16
  • I don't know.. did you add the user to the instance? Something like that: newdoc = Document(docfile = request.FILES['docfile'], user = request.user)
    – cor
    Jun 10, 2014 at 17:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.