Answer the question
In order to leave comments, you need to log in
Uploading files in Python 2.7 to a specific directory?
Hello, please help me understand.
My question is sure to seem simple to many, but I can not find the perfect solution. The Django project has a form with a field through which the user can upload one or more images. In the form, after clicking the submit button, you need to upload files to a specific directory. In my particular case, the form inherits from Form, not ModelForm.
Question : How to load these files in Python 2.7? Please tell me...
forms.py:
from django import forms
class ImageForm(forms.Form):
image_field = forms.ImageField(widget=forms.FileInput(attrs={'multiple': True}), required=False)
def form_valid(self, form):
images = self.request.FILES.getlist('image_field')
if image in images:
# Записать все файлы в определенную директорию
Answer the question
In order to leave comments, you need to log in
From documentation :
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
for f in request.FILES.getlist('file_field'):
with open('/path/to/file/' + f.name, 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
return HttpResponseRedirect('/success/url/')
else:
form = UploadFileForm()
return render(request, 'upload.html', {'form': form})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question