Error - "Required field" in image upload using Django

Asked

Viewed 203 times

0

Guys, I’m developing an application with Django and after organizing the form I went to test the registration and the image upload field always has the same message: "Required field" no matter what type of photo I try to upload. Could someone help me?

formFunctionnario.html:

{% extends 'aplicacao/base.html' %}

{% load crispy_forms_tags %}

{% block content %}
  <form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form|crispy}}
    <button type="submit" class="btn btn-success">Salvar Funcionário</button>
  </form>
{% endblock %}

py.models:

class Funcionario(models.Model):
     nome = models.CharField(max_length=100)
     data_nascimento = models.DateField(null=True, blank=True)
     endereco = models.CharField(max_length=200)
     telefone = models.CharField(max_length=200)
     #relacionamento 1 para n(um depratamento tem vários funcionarios) (1 ou muitos funcionarios pertencem a 1 dep)
     departamento = models.ForeignKey(Departamento, on_delete=models.CASCADE)
     estado_civil = models.CharField(max_length=200)
     email = models.CharField(max_length=200)
     cpf = models.CharField(max_length=200)
     salario = models.DecimalField(max_digits=8, decimal_places=4)
     image = models.ImageField(upload_to='media/images/', height_field=None, width_field=None, max_length=100, null='true')
     

     class Meta:
         verbose_name_plural = 'Funcionarios'#difinir o nome em plural da entidade funcionario

    
     def __str__(self):
         return self.nome

form py.:

class FuncionarioForm(ModelForm):
    class Meta:
        model = Funcionario
        fields = ['nome', 'data_nascimento', 'endereco' , 'telefone', 'departamento', 'estado_civil' , 'email', 'cpf' , 'salario', 'image']

py views.:

class FuncionarioCreateView(CreateView):
    model = Funcionario
    fields = ('nome', 'data_nascimento', 'endereco', 'telefone', 'departamento', 'estado_civil', 'email', 'cpf', 'salario','image')
    template_name = 'aplicacao/formFuncionario.html'

1 answer

1

Hi, I’d say the problem is how you’re setting Null. Define it like this. What version of Django are you using? A note, the parameters set with 'None' are unnecessary, I did not put them in the example below.

image = models.ImageField(upload_to='media/images/', max_length=100, null=True)
     

Another option, not working the previous one. Uses a default, is what I always do. So I show an image while it is not uploaded, for most cases it serves.

image = models.ImageField(upload_to='media/images/', max_length=100, default='images/profile/avatar-default-icon.png')

Browser other questions tagged

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