D
D
dblmok_19972019-02-21 13:39:55
Django
dblmok_1997, 2019-02-21 13:39:55

Django. Uploading a file to the server. Validation issues?

Hello!
It seems that the topic is rather hackneyed, and quite a lot of material has been written on this issue, but something does not grow together.
Required: upload a file from the form on the page, process and save to another file/add to the database. Doesn't really matter. Let's dwell on the option with intermediate saving to a file.
forms.py

class UploadFileForm(forms.Form):
    title = forms.CharField(max_length=50)
    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 the 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>

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question