Search code examples
pythondjangoformsdjango-formsdjango-widget

django form custom attrs widget imagefield


I have a model Prova:

class Prova(models.Model):
    id = models.AutoField(primary_key=True)
    codice=  models.TextField(blank=True, null=True)  
    foto = models.ImageField(upload_to='stati/uploads/', blank=True)

and this is the form:

class ProvaForm(forms.ModelForm):
    class Meta:
        model = models.Prova
        fields = ('codice','foto',)
        widgets = {
            'codice': forms.Textarea(attrs={'rows':1, 'cols':15,
                                            'autofocus':'autofocus',
            }),
            'foto': forms.ClearableFileInput(attrs={'type': 'camera'}),

            }

the customization of the codice field is working, but not the foto. I want to change the type of html input from 'file' to specific image from 'camera'.

Tried also ImageField and

 'foto': forms.FileInput(attrs={'capture': 'camera'}),

What am I missing to get it like the pure html:

<input type="file" capture="camera" accept="image/*">

Solution

  • camera is not valid HTML for the value of the type attribute of an input element.

    If you do change it to <input type="camera" name="a-name-here" value="some-value">, then Chrome and FF will render it as a text input, while your ProvaForm expects a file (an ImageField), resulting in a failed validation. Of course you can override the validation part, by writting you own one, but what's the point of using an ImageField from the start if instead this field is going to be rendered as a text?

    Check here for the possible values of the type attribute of an input element.