Home > Back-end >  Django file upload returns None
Django file upload returns None

Time:01-04

I'm trying to learn Python and Django, when I try to upload a file in my form Django detect my file as "None".

forms.py:

from django import forms

class FormularioTrabajo(forms.Form):
    email = forms.EmailField(label="Correo Electrónico:", max_length=254)
    Currículum = forms.FileField()

views.py:

In views I want to save the file uploaded in the directory /media/

def trabaja(request):
        if request.method == 'POST':
                form = FormularioTrabajo(data=request.POST, files=request.FILES)
                if form.is_valid():
                        file = request.FILES.get('file', None)
                        if file is not None:
                                file_name = file.name
                                file_path = '/media/'   file_name
                                with open(file_path, 'wb ') as destination:
                                        for chunk in file.chunks:
                                                destination.write(chunk)
                                form.save()
                                return HttpResponseRedirect(reverse("miapp:index"))
                        else:
                                return HttpResponse('None')
        else:
            form = FormularioTrabajo()
        return render(request, "web/trabajar.html", {'form':form})

This is my template html:

{% load bootstrap5 %}
{% bootstrap_css %}
{% bootstrap_javascript %}
{% bootstrap_messages %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    {% load static %}
    <link rel="stylesheet" href="{% static '/style.css' %}">
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
    <title>Trabaja con nosotros</title>
</head>
<body>
    <header>
        <br>
        <ul>
            <li><a href="conocernos.html">Conócenos</a></li>
            <li><a href="login.html">Inicio de Sesión</a></li>
            <li><a href="signup.html">Registro de usuario</a></li>
            <li><a href="contacto.html">Contacta con nosotros</a></li>
        </ul>
        {% load static %}
      <a href="index.html"><img src="{% static 'img/logo.PNG'%}" ></a>
    </header>
    <div >
        <h3>Solicitud de Trabajo</h3>
        <form id="contactForm" method="post" enctype="multipart/form-data">
          {% csrf_token %}
          {% bootstrap_form form %}
          {% buttons %} 
        <button  type="submit">Submit</button>
          {% endbuttons %}
        </form>
      </div>
</body> 
</html>

CodePudding user response:

Please correct this line

if form.is_valid():
   file = request.FILES.get('Currículum', None)
  • Related