Error loading file in html form

1

I am creating an application using django where files should be uploaded and these will be saved in the folder of a project.

The problem is that when I fill out the form from the admin of django it allows me to save the file without problems, but when I do it from the html form view it does not load the file.

model.py :

def content_file_name(instance, filename):
    ext = filename.split('.')[-1]
    filename = '%s %s %s.%s' % (instance.tipoSoporte, instance.codigoSoporte, instance.cargado, ext) 
    return '/'.join([str(instance.idProyecto), str("Legales"), filename])
class SoporteLegal(models.Model):
    idProyecto = models.ForeignKey(Proyecto, null=True, on_delete=models.SET_NULL)
    soporte = (
        ('01 Contrato','Contrato'),
        ('06 Otros avales', 'Otros avales'),
        )
    tipoSoporte = models.CharField('Tipo de soporte', max_length=50, choices=soporte, blank=False)
    codigoSoporte = models.CharField('Número de soporte', max_length=30, blank=True)
    cargado = models.DateField(auto_now=True)
    archivoSoporte = models.FileField(upload_to=content_file_name, validators=[validarExtensionValidaLegales], blank=False)
    def __str__(self):
        return str(self.idProyecto) + " - " + str(self.tipoSoporte) + " - " + str(self.codigoSoporte)

views.py :

def ResgistrarSoporteLegale(request):
    titulo = "Registro Soportes legales"

    form = RegistroSoporteLegal(request.POST, request.FILES)
    if form.is_valid():
        instance = form.save(commit=False)
        print(instance)
        form.save()

    context = {
        "titulo": titulo,
        "form": form,
        }
    return render(request, "proyecto/registrosoportelegal.html", context)

forms.py :

class RegistroSoporteLegal(forms.ModelForm):
    class Meta:
        model = SoporteLegal
        fields ='__all__'

In the html :

<div class="container-fluid">
    <form method='POST' action="">{% csrf_token %}

            {{ form.as_p }}

    <input type="submit" value='Registrar'>
    </form>
</div>

As I said, everything works fine but at the moment of trying to register the support from the html form in the FileField field that will be uploaded, the alert appears that "this field is required" and does not save the form.

I ask you to please help me and I am attentive to you.

    
asked by Sebastián Mejía Ríos 24.03.2018 в 21:55
source

1 answer

0

Fixed: it was necessary to add in% html <form enctype="multipart/form-data" method="POST" action="">

    
answered by 27.03.2018 в 02:43