【问题标题】:Django user specific foldersDjango 用户特定文件夹
【发布时间】:2014-07-31 13:09:25
【问题描述】:

我想为用户上传的文件创建用户特定的文件夹。这是我的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,而是将用户名粘贴在其中的某处。有没有办法做到这一点?

【问题讨论】:

  • 在 form.is_valid() 之后传递当前用户:user = request.user 并将其作为参数传递给您的模型。

标签: python django directory


【解决方案1】:

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

【讨论】:

  • 感谢您的回复,但我一定是做错了什么。我得到“'文档'对象没有属性'用户'”
  • 这是因为您的 Document 模型没有用户字段。
  • 所以我必须先用id定义用户对象?
  • 对不起,我不够清楚,这会返回错误:“没有这样的列:upload_document.user_id”
  • 我不知道..您是否将用户添加到实例?类似的东西:newdoc = Document(docfile = request.FILES['docfile'], user = request.user)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-07
  • 1970-01-01
  • 2018-10-23
  • 2017-02-02
  • 2016-09-18
  • 2021-10-10
相关资源
最近更新 更多