Re: [問題] django 檔案上傳
※ 引述《lauer (Enjoy it)》之銘言:
: 以下是 Model 的內容
: class Photo(forms.Form):
: #Title = forms.CharField(max_length=50)
: file_up = forms.FileField()
title 必須是not null的 然後你沒有給值當然不會過
如果你改成 title = forms.CharField(null=True, blank=True, max_length=50)
就可以不給值
請參考下面連結
http://docs.djangoproject.com/en/dev/ref/models/fields/
http://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.is_valid
你要指定上傳位置是在FileField中的upload_to設定
還有settings.py中的MEDIA_ROOT
: 上面移除了原本網頁的 title
: 以下是 template 的內容
: <form method="POST" enctype="multipart/form-data" action="/upload/">
: <input name="file_up" type="file">
: <input name="ok" type="submit" value="確定上傳此檔案">
: </form>
: 以下是 python code
: def handle_uploaded_file( file ):
: destination = open('downloadfile/%s' %( file ) ,'ab') # 修改了這部分
: for chunk in f.chunks():
: destination.write(chunk)
: destination.close()
: 上面這是寫入檔案,我修改了開啟檔案的部分後,已經可以正確上傳
: def upload_file(request):
: if request.method == 'POST':
: form = Photo(request.POST,request.FILES)
: if form.is_valid():
: handle_uploaded_file(request.FILES['file_up'])
: return render_to_response('upload.html')
else:
print form.errors
加入這行就可以看到為什麼表單驗證不會過
: else:
: form = Photo()
: return render_to_response('upload.html')
: 目前的問題是在官網範例為何當多了 Title 則 form.is_valid() 不會為 True
: 還有想請教今天如果我想在寫入檔案的資料夾 (downloadfile) 由程式在動態加入
: 一個子資料夾,請問該如何實作呢?
: 麻煩各位了!謝謝 辛苦了!
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.119.203.55
討論串 (同標題文章)
Python 近期熱門文章
PTT數位生活區 即時熱門文章