我完全沉迷於此,而且必須做一些令人難以置信的蠢事。我正試圖在Django項目上簡單地上傳文件。問題似乎是沒有表單數據傳遞給服務器 - 只有csrf標記。我在Mac上運行Django 1.5.1,python 2.7,virtualenv,並使用內置的Django開發服務器。request.FILES文件上傳時總是空
我的HTML形式是:
{% load url from future %}
<form enctype="multipart/form-data" method="POST" action="{% url 'showreport' %}">
{% csrf_token %}
<label>Upload grade csv file: </label>
<input type="hidden" id="testing" value="maybe" />
<input type="file" id="grade_csv" />
<input type="submit" value="Generate Report" />
</form>
我的模型:
from django.db import models
class Document(models.Model):
file = models.FileField(upload_to='/media/', blank=True, null=True)
我forms.py:
from django import forms
from .models import Document
class DocumentForm(forms.Form):
"""
to handle uploading grades csv file
"""
class Meta:
models = Document
我views.py:
def report(request):
"""
Process the CSV file to remove inactive students
Manipulate to get right JSON format
Chart the results
"""
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newfile = Document(file = request.FILES['file'])
newfile.save()
classdata = {}
studentdata = {}
return render(request, 'report/showreport.html', { 'classdata': classdata, 'studentdata': studentdata })
else:
form = UploadFileForm()
return render(request, 'report/index.html', { 'form': form })
我花了幾個小時尋找解決方案,但似乎沒有任何工作。 I have the enctype set correctly(我認爲),I am using input type 'submit' for the form和I am binding the form data to my model(沒關係,因爲request.FILES是空的)。我也嘗試在每個this Django newbie page的表單操作中使用直接網址(action ='/ report/showreport /'),但這沒有什麼區別。據我所知,沒有其他腳本綁定到表單提交操作並覆蓋默認操作。
我也意識到,上面的代碼應該最像是request.FILES ['grades_csv']以匹配表單的輸入ID ...但這也沒有關係,因爲request.FILES是空的。
在試圖調試時,我已經在我的視圖中的if request.method ==「POST」之前設置了一個pdb跟蹤。使用控制檯,我可以看到我的request.POST不包含我隱藏的「測試」輸入,並且該request.FILES爲空。當我在瀏覽器中運行它時,它只是返回到我的表單頁面,本質上說我的表單無效。我PDB結果在這裏:
(Pdb) request.FILES
(Pdb) <MultiValueDict: {}>
(Pdb) request.POST['testing']
(Pdb) *** MultiValueDictKeyError: "Key 'testing' not found in <QueryDict: {u'csrfmiddlewaretoken': [u'0tGCChxa3Po619dCi114Sb9jmWRt82aj']}>"
(Pdb) request.POST
<QueryDict: {u'csrfmiddlewaretoken': [u'0tGCChxa3Po619dCi114Sb9jmWRt82aj']}>
如果我嘗試訪問我的views.py request.FILES任何檢查的形式是有效的,我得到這個錯誤:
"Key 'file' not found in <MultiValueDict: {}>"
我難倒和感謝爲什麼我無法得到這個工作的任何幫助 - 它看起來應該很簡單。我可以使用pdb手動創建並寫入我的項目目錄中的文件,所以我不認爲權限是問題...問題出現在表單中?
看起來像您的HTML形式缺少的名稱與輸入字段屬性,嘗試像 – Jingo
有幾件事對我來說很可疑。您的表單輸入缺少'name'屬性。您正在對'forms.Form'進行子分類,但有一個'Meta'類,表示您需要'forms.ModelForm'。如果您打算使用模型表單,則不需要實例化Document對象,因爲表單會爲您執行此操作。 –
天才 - 謝謝!如果您將它作爲一個提交,我會很樂意接受... – user