Reputation: 512
I want to upload an image from a form without model. I've tried to make:
In the template: det.html
Upload image
<form enctype="multipart/form-data" action="" method="post">{% csrf_token %}
<input type="file" name="myfile" id="myfile" />
<input type="submit" value="Upload image">
</form>
In the views, I have:
def fileupload(request):
return responsewrapper('personne/det.html', locals(),request)
def handle_uploaded_file(f):
filename = file._get_name()
destination = open('/personne/static/personne/%s'%filename, 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
def submitfilecontent(request):
handle_uploaded_file(request.FILES['myfile'])
return HttpResponseRedirect("/successupload")
The error is: Method Not Allowed (POST): /fr/detect/
my urls:
urlpatterns += i18n_patterns(
url(r'^admin/', admin.site.urls, name="admin"),
url(r'^$', views.IndexView.as_view(), name="homepage"),
url(r'^detect/$', views.DetectView.as_view(), name="detection"),
url(r'^login/$', auth_views.login, name="login"),
url(r'^logout/$', auth_views.logout, name="logout"),
url(r'^register/',views.addUser, name='register'),
)+ i18n_patterns('', (r'^(?P<path>.*)$', 'django.views.static.serve', {'document_root': MEDIA_ROOT, 'show_indexes': True}))
Update:
in urls.py, I added:
url(r'^submitfilecontent/$', submitfilecontent, name="submit-file-content"),
in the template:
<form enctype="multipart/form-data" action="/submitfilecontent/" method="post">
The new error: MultiValueDictKeyError: "'myfile'"
Upvotes: 0
Views: 1931
Reputation: 512
Views.py:
def submitfilecontent(request):
ext_allowed = ['gif', 'jpg', 'jpeg', 'png']
today = datetime.datetime.today()
save_dir = 'personne/static/personne/%d/%d/%d/' % (today.year, today.month, today.day)
save_path = os.path.join(settings.MEDIA_ROOT, save_dir)
save_url = os.path.join(settings.MEDIA_URL, save_dir)
if request.method == 'POST':
file = request.FILES['myfile']
ext = file.name.split('.').pop()
if not os.path.isdir(save_path):
os.makedirs(save_path)
new_file = '%s.%s' % (int(time.time()), ext)
destination = open(save_path+new_file, 'wb+')
for chunk in file.chunks():
destination.write(chunk)
destination.close()
return HttpResponse("Upload Succsefull to URL:%s" % (save_url+new_file) )
else:
raise Http404
Upvotes: 0
Reputation: 27466
Please add a url(below) in urls.
url(r'^submitfilecontent/$', submitfilecontent, name="submit-file-content"),
and in HTML, add the action url
<form enctype="multipart/form-data" action="/submitfilecontent/" method="post">{% csrf_token %}
Upvotes: 1