Reputation: 6693
I learned Django online and practice how to upload file There is have error
[Errno 2] No such file or directory:
here is my file structure ( The '--' I use means 'directory' )
web08
--blog
--templates
regist.html
__init__.py
admin.py
models.py
tests.py
views.py
--web08
--upload
__init__.py
settings.py
urls.py
wsgi.py
manage.py
I don't know where to put the upload
directery
Please teach me,Thank you!
views.py:
class UserForm(forms.Form):
username = forms.CharField()
headImg = forms.FileField()
def regist(req):
if req.method == 'POST':
uf = UserForm(req.POST,req.FILES)
if uf.is_valid():
fp = file('/upload/'+uf.cleaned_data['headImg'].name,'wb')
s = uf.cleaned_data['headImg'].read()
fp.write(s)
fp.close()
return HttpResponse('ok')
else:
uf = UserForm()
return render_to_response('regist.html',{'uf':uf})
Upvotes: 1
Views: 4661
Reputation: 15388
In this line:
fp = file('/upload/'+uf.cleaned_data['headImg'].name,'wb')
You are refererring to an absolute path /upload/
that seems not to exist. Also, please use os.path.join
to combine path components.
In addition this might be a major security problem as you are using possibly unfiltered user input cleaned_data['headImg'].name
for the filename. This probably allows the user to overwrite any file in your /upload/
directory or --even worse using relative paths-- any file that your django server has write access to.
Where to put your upload directory depends on the question if you want your uploaded files to be visible to the outside world or only accessible by the server.
For the former, you should use django's media storage engine. This is often on the file system in a directory named by the django setting MEDIA_ROOT
. The media storage directory is meant to be directly served by the production web server without going through django first.
Please also read django's documentation on Managing Files.
If you want a custom directory for uploaded files (e.g. because you do not want them publicly available), define your own storage engine:
from django.core.files.storage import FileSystemStorage
upload_storage = FileSystemStorage(uploads_dir)
and use that in your file field:
headImg = forms.ImageField(upload_to=upload_storage)
[...]
headImg = uf.cleaned_data['headImg']
headImg.save() # this will save the image to the storage engine.
# no need to do this manually
There is rarely a need to access file system paths directly in django.
Upvotes: 2