目次
ソース
settings.pyにMEDIA_ROOLを追加
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
forms.pyを作成
from django import forms
class UploadFileForm(forms.Form):
file = forms.FileField()
views.pyにupload_fileファンクションを追加
from django.conf import settings
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import UploadFileForm
def handle_uploaded_file(f, filename):
path = settings.MEDIA_ROOT + '/upload/'
with open(path + filename, 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
filename = request.FILES['file'].name
handle_uploaded_file(request.FILES['file'], filename=filename)
else:
form = UploadFileForm()
return render(request, 'upload.html', {'form': form})
ursls.pyにMEDIA_URLとMEDIA_ROOTを設定。
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from . import views
urlpatterns = [
path('', views.upload_file, name='upload_file'),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
upload.htmlをシンプルに用意。
<form method="POST" action="{% url 'upload_file' %}" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<p>
<input type="submit" name="submit" value="upload">
</p>
</form>
簡易解説
- media/upload/配下にファイルに格納されます
- ファイル拡張子はなんでもOKです。
- views.pyに定義されているhandle_uploaded_file関数は別ファイルに書くことをオススメします。