#python #django #file-upload #django-forms
Вопрос:
У меня есть следующий код:
urls.py:
urlpatterns = [
...
url(r'^upload_file', FileFieldFormView.as_view(), name='upload_file'),
url(r'^success', lambda request: HttpResponse('Hello World!'), name='hello_world'),
]
upload_file.py:
from django.views.generic.edit import FormView
from ..forms import FileFieldForm
import ipdb
def handle_uploaded_file(f):
ipdb.set_trace()
with open(f.name, 'wb ') as destination:
for chunk in f.chunks():
destination.write(chunk)
class FileFieldFormView(FormView):
form_class = FileFieldForm
template_name = 'reports/upload_file.html' # Replace with your template.
success_url = '/reports/success' # Replace with your URL or reverse().
def post(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
files = request.FILES.getlist('file_field')
if form.is_valid():
for f in files:
print("hello")
handle_uploaded_file(f)
return self.form_valid(form)
else:
print("invalidated")
return self.form_invalid(form)
forms.py:
from django import forms
class FileFieldForm(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
и upload_file.html шаблон:
{% extends "core/layout.html" %}
{% block content %}
<br/>
<h3>{{ title }}</h3>
<br/>
{% block controls %}{% endblock %}
<form enctype="multipart/form-data" method="post">
{% csrf_token %}
{{ form.as_table }}
<button type="submit">Upload</button>
</form>
{% endblock %}
В файлах переменная в upload_file.py Я получаю список временных загруженных файлов и просто хочу сохранить их все в определенную папку, предварительно проверив их тип. Как я могу это сделать в функции handle_uploaded_file?