setting.py

PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media') MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') STATIC_URL = '/static/' 

the form

 <form action="" method="post" enctype="multipart/form-data">{% csrf_token %} {{ form }} <input type="submit" value="Submit" /> </form> 

views.py

 def uploads(request): if request.method == 'POST': form = upload(request.POST, request.FILES) return HttpResponse(request.FILES['file'].temporary_file_path) else: form = upload() return render_to_response('ff.html', {'form': form}) 

request.FILES['file'].temporary_file_path should return the path to the temporary file. There is no file in the media folder, and only the > sign is displayed in the browser

in the form model, only the FileField() field. When upload_to to the console, the error __init__() got an unexpected keyword argument 'upload_to'

  • one
    However, a charset is not a file path. You can display, for example, name - the name of the downloaded file. However, that is not the point. The file is saved to the location specified in the upload_to after calling form.save() , which you do not have. Give, by the way, another code for upload. - velikodniy
  • upload_to is in the file field in the model (ie, in the description of the database table). If you create a form based on a model, then everything is easy. If you just made a form, then the file must be processed manually. For example, insert a command to copy to the right place. - velikodniy
  • Added in response a couple of paragraphs about file copying - velikodniy

1 answer 1

Briefly: the file loaded through the form must be processed, which your program does not do .

When you upload a file, Django first places it in a temporary storage. Small files are placed in memory, large files are located in the system temporary directory (on Linux, this is /tmp/ ).

Example (UploadFileForm is a form containing a file field of type FileField):

 def upload_file(request): # Если метод POST if request.method == 'POST': # Заполняем форму полученными данными form = UploadFileForm(request.POST, request.FILES) # Если данные валидны if form.is_valid(): # обрабатываем файл handle_uploaded_file(request.FILES['file']) # перенаправляем на другую страницу return HttpResponseRedirect('/success/url/') # Если другой метод (обычно GET) else: form = UploadFileForm() # Выводим форму загрузки return render_to_response('upload.html', {'form': form}) 

Redirection is done so that when the page is refreshed, the file is not downloaded again. handle_uploaded_file is a file processing function, you need to write it yourself.

An example of copying the contents of the resulting file into the file /srv/media/data.txt :

 def handle_uploaded_file(f): with open('/srv/media/data.txt', 'wb+') as dest: for chunk in f.chunks(): dest.write(chunk) 

It is necessary to use chunks , since copying in parts loads the system less. Just copying from a temporary folder is also not suitable, since the file can be loaded into memory.

The path by which the file will be saved can be generated from MEDIA_ROOT and the name of the downloaded file using os.path.join .

You can process the file in different ways. You can read its entire content using the read() method or in parts using the chunks() method and do something with it. But more often than not, the file is simply saved to a directory where it will be stored later.

Django also provides a convenient way. If the file is also stored in the model, then it can be saved to the specified location with a single call. To do this, in the model you create a FileField field of type FileField with the upload_to argument containing the path that the file will be placed on. If you created a form based on a model (that is, using a ModelForm ), then the command

 form.save() 

to save the file to the specified location. You can also upload files through the admin panel.

Uploading files to Django