Get file path from the request.POST in Django

0

I want to obtain the path of a file that I upload using a form but when printing the field returns a type None .

My models.py is this

class Insumo(models.Model):
    nombre = models.CharField(max_length=50)
    file = models.FileField()
    def __str__(self):
        return self.nombre

my forms.py is:

class ImportData(ModelForm):
    class Meta:
            model = Insumo
            fields = ['nombre', 'file']

my views.py is this

def carga_data(request):
    if request.method == 'POST':
        formulario = ImportData(request.POST, request.FILES)
        if formulario.is_valid():
            name=request.POST.get('nombre')
            ruta=request.POST.get('file')
            print (name)
            print (ruta)
            return render(request,"carga_data.html", {'form': formulario})
    else:
        formulario = ImportData()
    return render(request, "carga_data.html",{'form': formulario})

and my template is this:

<form method="POST" enctype="multipart/form-data"> {% csrf_token %}                         
        {{form.as_p}}                       
        <input type="submit" value="Cargar Informacion">
</form>

and the result of the print(name) and print(ruta) after submitting the submit is

I need the file path instead of None

Thanks

    
asked by Javier Valero 13.12.2017 в 15:42
source

1 answer

0

To get the file path it was necessary to get the request.FILES instead of request.POST on the views.py, like this:

def carga_data(request):
    if request.method == 'POST':
        formulario = ImportData(request.POST, request.FILES)
        if formulario.is_valid():
            ruta=request.FILES.get('file') #Retorna la ruta del archivo
            print(ruta)

            return render(request,"carga_data.html", {'form': formulario})
    else:
        formulario = ImportData()
    return render(request, "carga_data.html",{'form': formulario})
    
answered by 13.12.2017 в 15:59