newbieProgrammer newbieProgrammer - 3 months ago 34
Python Question

This field is required. Error with ImageField and FileField on Django

I am new on Django, I am using Django 1.6.1 and in one of my form I get the next error

This field is required.


I don't understand why I get this error, my form is very basic, so my Model, the statement who launch this error is form.is_valid(), but I don't know why.
Some help would be apreciate.

my views is:

if request.method == 'POST':
form = campoImagenForm(request.POST, request.FILES)
if form.is_valid():
articulo = form.save(commit=False)
articulo.item = item
articulo.atributo = atributo
articulo.save()
return HttpResponseRedirect('/workproject/' + str(project.id))


my Form is:

class campoImagenForm(forms.ModelForm):
class Meta:
model = campoImagen
fields = ('imagen',)


my Model is:

class campoImagen(models.Model):
item = models.ForeignKey(ItemBase)
atributo = models.ForeignKey(TipoItem)
imagen = models.ImageField(verbose_name='Imagen', upload_to='archivos')
version = models.IntegerField()


I don't have a clue of why I get such an error.

Answer

At first, in your model make your fields empty and nullable:

class campoImagen(models.Model):
    # [...]
    imagen = models.ImageField(verbose_name='Imagen', upload_to='archivos', null=True, blank=True)

Then in your model form alter the required parameter of your field:

class campoImagenForm(forms.ModelForm):
    class Meta:
        model = campoImagen
        fields = ('imagen',)

    def __init__(self, *args, **kwargs):
        super(campoImagenForm, self).__init__(*args, **kwargs)
        self.fields['imagen'].required = False

The model part is, however, obligatory. Otherwise you might be getting database inconsistency errors.

Keep in mind that blank and null are different things. They do, however, work well together and should give you what you want.

Comments