作者superGA (kid...)
看板Python
标题Re: [问题] django 档案上传
时间Wed Jun 3 17:32:16 2009
※ 引述《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