Jorge López
Jorge López

Reputation: 523

Django CreateView Model Form not uploading File

the problem that I have is that my Model Form is not uploading a file, I had it working and after adding more code now is not working, this is what it happens: It uploads/save all the other fields except for the file, the strange thing is that if I do it from the admin site it does work. I will add that is not writing the path in the database column.

models.py

class Polizas(models.Model):

    nombre = models.CharField(max_length=30, blank=True, null=True)
    numero = models.CharField(max_length=30, unique=True)
    aseguradora = models.CharField(max_length=20, blank=True, null=True)
    carro = models.ForeignKey(
        Carros, on_delete=models.CASCADE, blank=True, null=True)
    inicio_poliza = models.DateField(
        auto_now=False, auto_now_add=False, blank=True, null=True)
    fin_poliza = models.DateField(
        auto_now=False, auto_now_add=False, blank=True, null=True)
    documento = models.FileField(upload_to='polizas/', blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name_plural = "Polizas"
        ordering = ['nombre']

    def __str__(self):
        return self.nombre

    def get_absolute_url(self):
        return reverse('polizas')

forms.py

class PostPolizas(forms.ModelForm):
    class Meta:
        model = Polizas
        fields = ('nombre', 'numero', 'aseguradora', 'carro', 'inicio_poliza',
                  'fin_poliza', 'documento')
        widgets = {'inicio_poliza': forms.DateInput(attrs={'type': 'date'}),
                   'fin_poliza': forms.DateInput(attrs={'type': 'date'})
                   }

views.py

class PolizaCreate(LoginRequiredMixin, CreateView):
    login_url = '/login/'
    redirect_field_name = 'redirect_to'

    form_class = PostPolizas
    template_name = "add_insurance.html"

Terminal

[06/May/2020 22:32:17] "POST /insurance/add/ HTTP/1.1" 200 4557
[06/May/2020 22:32:25] "POST /insurance/add/ HTTP/1.1" 302 0

I have tried to validate the form and it is not working, this is error is happening in my other model forms that upload files, it uploads the text fields and dates but not the files.

Upvotes: 1

Views: 1074

Answers (2)

themrinalsinha
themrinalsinha

Reputation: 651

By default forms only pass request.POST since you are uploading a file you have to pass request.FILES into the form's constructor

Follow: https://docs.djangoproject.com/en/2.2/topics/http/file-uploads/

Upvotes: 0

Leandro L
Leandro L

Reputation: 171

Try adding enctype="multipart/form-data" like this:

<form enctype="multipart/form-data" method="post">
    {% csrf_token%}
    <table> {{form}} </table>
    <input type="submit" value="Post">
</form>

in the template form.

Upvotes: 3

Related Questions