簡體   English   中英

使用Django上傳文件

[英]uploading a file using django

我正在使用django開發用於在服務器上上傳文件的應用程序。 我分別在forms.py和models.py文件中定義了一個表單和一個模型,如下所示(分別):

from django import forms

class DocumentForm(forms.Form):
    docfile = forms.FileField(
        label=''
    )

並在models.py中:

from django.db import models

# Create your models here.

    class Document(models.Model):
        docfile = models.FileField(upload_to='targetdir')

在我的HTML文件中,我的表單是:

    <form  class="myclass" action="submit" method="post">
    {% csrf_token %}

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


        <br />
            <input font-size="50px" style="zoom:1.5"  class="myclass" dir="rtl" type="submit" value="upload"  id="button" class="top-menu" onclick="pythonhandler()" />

現在,每當我提交表單並想要通過以下代碼在服務器上接收上傳的文件時,我都會得到“

raise MultiValueDictKeyError(repr(key))
MultiValueDictKeyError: "'docfile'""

錯誤。 我的views.py文件:

def pythonhandler(request):

    if request.method == 'POST':
        try:
                    data = request.FILES.get('docfile') 
                    with open(os.getcwd()+'/mydirectory/'+request.FILES['docfile'].name, 'wb+') as destination:
                        for chunk in request.FILES['docfile'].chunks():
                            destination.write(chunk)

我在thisthisthis問題中執行了上述步驟,但是我再次收到此錯誤!

在您的視圖功能中

def pythonhandler(request):
data = DocumentForm(request.POST, request.FILES)

並在您的html文件中

<form  class="myclass" action="submit" enctype="multipart/form-data" method="post">
    {% csrf_token %}

    <p>
                {{ form.docfile.errors }}
                {{ form.docfile }}
</p>
            <input type="submit" value="upload" id="button" class="top-menu" onclick="pythonhandler()" />

我在HTML文件的表單標記中錯過了enctype =“ multipart / form-data”命令。 因此,HTML文件中的表單必須如下所示:

<form  class="myclass" action="submit" enctype="multipart/form-data" method="post">
    {% csrf_token %}

    <p>
                {{ form.docfile.errors }}
                {{ form.docfile }}
</p>
            <input type="submit" value="upload" id="button" class="top-menu" onclick="pythonhandler()" />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM