Save a file using a view function on Django

Asked

Viewed 297 times

1

I have this following HTML, which is a form with an input for a file and Submit button:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document Classifier</title>
</head>
<body>

<div>
    <h1> Document Classifier </h1>
</div>

<form name="form" method="POST">
    {% csrf_token %}

    <input type="file" name="file">
    <button type="submit" class="btn btn-success">Classify</button>
</form>

I’m trying to save this file by calling the method Classify view:

from django.shortcuts import render
from .forms import DocumentForm
from .models import Document

# Create your views here.


def classify(request):
    classified = False

    print(request.FILES)

    if request.method == "POST":
        my_document_form = DocumentForm(request.POST, request.FILES)

        if my_document_form.is_valid():
            doc = Document()
            doc.file = DocumentForm.cleaned_data["file"]
            doc.save()
            classified = True
        else:
            my_document_form = DocumentForm()

        return render(request, 'documents/saved.html', locals())

    return render(request, 'documents/base.html', {})

However, the request.FILE is coming empty, meaning the file is not coming. What can it be? I’ve tried several things. In the print I put inside the method, appears Multivaluedict: {} in the logs.

1 answer

1


I don’t know if there are errors in the back end (this is the problem of the Jango abstraction level, hard to detect errors without knowing the context), but something is missing in the front end. Alter block:

<form name="form" method="POST">
    {% csrf_token %}

for:

<form method="post" enctype="multipart/form-data">
    {% csrf_token %}

Take the test, see if you go now. :-)

The enctype attribute specifies how a data form should be "encoded" (would "encode" the translation?) when submitted to the server.

application/x-www-form-urlencoded:
Default, "encoding before sending characters (spaces are converted to "+" symbols and special characters are converted to ASCII values in Hexa.

Multipart/form-date:
Characters will not be encoded. Required when the form is used to upload files

text/Plain:
Spaces are converted to "+", but special characters are not encoded.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.