It seems that the topic is quite a bit annoying, and quite a lot of material is written on this issue, but something does not grow together. It is necessary: ​​load the file from the form on the page, process and save to another file / add to the database. Whatever. Let's stop on a variant with preservation intermediate in a file.

forms.py

class UploadFileForm(forms.Form): title = forms.CharField(max_length=50, required=False) file = forms.FileField() 

views.py

 def uploadFile(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['file']) return HttpResponseRedirect('/success/url/') else: form = UploadFileForm() return render_to_response('upload/main.html', {'form': form}) def handle_uploaded_file(f): destination = open('addfile', 'wb+') for chunk in f.chunks(): destination.write(chunk) destination.close() 

Everything is processed, no errors come out, but nothing happens at the same time. The problem is that the program does not enter if with validation.

The form itself:

 <form enctype="multipart/form-data" action="/upload/uploadFile" method="post"> {% csrf_token %} <label for="addfileids">Добавить файл </label> <input id="addfileids" type="file" name="addfileids"> <button type="submit" value="Добавить", class="btn btn-primary">Добавить</button> </form> 
  • 2
    Naturally, you do not have a field in the form named file . - Sergey Gornostaev
  • Add {{form}} to the template, then it should work. If you want to manually add form fields, then look at what id fields on the form that is displayed by Django itself and specify the same ones. - Andrey

1 answer 1

try this

  <form enctype="multipart/form-data" action="/upload/uploadFile" method="post"> {% csrf_token %} <label>Добавить файл </label> {{ form.as_p }} <button type="submit" value="Добавить", class="btn btn-primary">Добавить</button> </form>