Django用户特定的文件夹

时间:2014-06-10 16:47:41

标签: python django directory

我想为用户上传的文件创建用户特定的文件夹。这是我的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)
    )

这是我的models.py

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

我的想法是这样的。而不是命名它uploads/%Y.%m.%d我将用户名固定在那里。有没有办法做到这一点?

1 个答案:

答案 0 :(得分:0)

我在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