简体   繁体   中英

Django user specific folders

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM