/ myapp / download / [Errno 13]的PermissionError权限被拒绝:

时间:2018-04-06 04:40:38

标签: python django

我是django和python的新手,并使用django开发一个简单的上传/下载网络应用程序。到目前为止,我已经设法完成上传功能,但它有效,但我下载上传的文件有困难。代码似乎工作但我收到'Permission Denied'错误。这些是我使用的代码:

(views.py)

def list(request):
#file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
           doc_file = Document(docfile=request.FILES['docfile'])
           print(doc_file)
           print(doc_file.uploaded_at)
           doc_file.save()

          # Redirect to the document list after POST
          return HttpResponseRedirect(reverse('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(
        request,
        'list.html',
        {'documents': documents, 'form': form}
    )


def download(request):
   file_name = request.GET.get(' ')
   print(file_name)
   path_to_file = settings.MEDIA_ROOT + '/' + file_name
   print(path_to_file)
   with open(path_to_file, 'rb') as fh:
      response = HttpResponse(fh.read(), content_type='application/force-download')
      response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name)
      response['X-Sendfile'] = smart_str(path_to_file)
      return response

models.py

class Document(models.Model):
    docfile = models.FileField(upload_to='documents/%Y/%m/%d')
    uploaded_at = models.DateTimeField(default=datetime.now, blank=True)

  def size(self):
      filesize = self.docfile.size
      return filesize

  def filename(self):
      filename = self.docfile.name
      return filename.replace("documents/", "")

list.html

     <!DOCTYPE html>
  <html>
     <head>
        <meta charset="utf-8">
        <title>File upload/download</title>
        <style>
        table {
          border-spacing: 5;
          width: 80%;
          border: 5px dotted black;
      }

    th {
        cursor: pointer;
    }

    th, td {
        text-align: middle;
        padding: 15px;
    }

    body {
        background-color: lightblue;
    }
    </style>

</head>

<body>

        <!-- Upload form. Note enctype attribute! -->
    <form action="{% url 'list' %}" method="post" enctype="multipart/form-data">
        {% csrf_token %}

        <p>{{ form.docfile.label_tag }}</p>

        <p> {{ form.docfile }}</p>

        <p><input type="submit" value="Upload"/></p>

    </form>
    <!-- List of uploaded documents -->
    {% if documents %}
        <ul>

            <table id="tbl" border="1">
            <thead>
                <tr>
            <th >File Name</th>
            <th >File Size</th>
            <th >Uploaded Time</th>
                </tr>
            </thead>
            {% for document in documents %}

            <tbody>
            <tr>
                <td><a href="http://127.0.0.1:8000/myapp/download/? ={{ document.document }}">{{ document.filename }}  </a></td>
                <td>{{document.size|filesizeformat}} </td>
                <td>{{document.uploaded_at}}</td>
            </tr>
            </tbody>

            {% endfor %}

            </table>

        </ul>
    {% else %}
        <p>not available.</p>
    {% endif %}


</body>

错误追溯:

Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/myapp/download/?%20=

Django Version: 2.0.4
Python Version: 3.6.5
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']



 Traceback:

 File "C:\Users\anonymous\PycharmProjects\djangos\env\lib\site- 
 packages\django\core\handlers\exception.py" in inner
 35.             response = get_response(request)

 File "C:\Users\anonymous\PycharmProjects\djangos\env\lib\site- 
 packages\django\core\handlers\base.py" in _get_response
  128.                 response = self.process_exception_by_middleware(e, 
 request)

 File "C:\Users\anonymous\PycharmProjects\djangos\env\lib\site- 
 packages\django\core\handlers\base.py" in _get_response
 126.                 response = wrapped_callback(request, *callback_args, 
 **callback_kwargs)

 File "C:\Users\anonymous\PycharmProjects\djangos\myproject\myapp\views.py" 
 in 
 download
 42.     with open(path_to_file, 'rb') as fh:

Exception Type: PermissionError at /myapp/download/
Exception Value: [Errno 13] Permission denied: 
'C:\\Users\\anonymous\\PycharmProjects\\djangos\\myproject\\media/'

0 个答案:

没有答案