File upload in Django
I'm trying to get Django to upload a file (keeping it simple, for now), but am having difficulties. Here's all of the relevant code (that I know of). Perhaps something is wrong with my settings.py? My code is pieces of various answers on Stack Overflow. I've checked here already.
When I select a file (~8.5mb file because I saw Django does something funny if it is under 2.5mb) and press Submit, I am brought to the Upload Success page, but can't seem to find my file anywhere in my project directory.
I am using the development runserver with apache running just for serving images.
settings.py
MEDIA_ROOT = '/Users/adam/Documents/workspace/sitename/media'
MEDIA_URL = 'http://127.0.0.1:8000/media/'
STATIC_ROOT = '/Library/WebServer/Documents/static/'
STATIC_URL = 'http://10.0.1.15/static/'
ADMIN_MEDIA_PRE开发者_StackOverflow社区FIX = '/media/admin/'
STATICFILES_DIRS = (
)
*the static URL is the address of my local apache webserver.
urls.py
urlpatterns = patterns('',
('^$', index),
('^uploadfile/$', uploadfile),
('^uploadsuccess/$', uploadsuccess),
)
if settings.DEBUG:
from django.views.static import serve
_media_url = settings.MEDIA_URL
if _media_url.startswith('/'):
_media_url = _media_url[1:]
urlpatterns += patterns('',
(r'^%s(?P<path>.*)$' % _media_url,
serve,
{'document_root': settings.MEDIA_ROOT}))
del(_media_url, serve)
views.py
def uploadsuccess(request):
return render_to_response('uploadsuccess.html', {})
class UploadFileForm(forms.Form):
file = forms.FileField()
def uploadfile(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploads(request.FILES['file'])
form.save()
return HttpResponseRedirect('/')
else:
form = UploadFileForm()
return render_to_response('fileupload.html', {'form': form}, context_instance=RequestContext(request))
def handle_uploads(file):
logging.debug("upload_here")
if file:
destination = open('/tmp/'+file.name, 'wb+')
for chunk in file.chunks():
destination.write(chunk)
destination.close()
fileupload.html
<html>
<body>
<h1>Upload a file</h1>
<form enctype="multipart/form-data" method="post" action="/uploadsuccess/">
{% csrf_token %}
<table>
{% for field in form %}
{{ field.label_tag }}
{{ field }}
{% endfor %}
</table>
<input type="submit" value="Submit" id="Save"/>
</form>
<body>
</html>
uploadsuccess.html
<html>
<body>
<h1>Upload Successful!</h1>
<body>
</html>
You are posting data to the wrong URL, change action="/uploadsuccess/"
to /uploadfile/
.
精彩评论