5

I want to create a form to upload and save videos from iOS Safari, which supports the "accept" attribute of the input tag, for example:

<input type=file accept="video/*">

lets you shoot and upload new video or select a video file on the device.

I've looked at the Django docs at: https://docs.djangoproject.com/en/dev/ref/forms/fields/#django.forms.FileField

but don't see where I can specify the "accept" attribute on input. Is this possible? Can I create the input tag in the template and still use Django form processing to accept the file?

Steve Nelson
  • 136
  • 1
  • 6

4 Answers4

11

Easy. In your model form, just make sure the FileInput widget gets created with the needed accept HTML attribute:

from django import forms

class VideoForm(forms.ModelForm):
    class Meta:
        model = Video
        exclude = []
        widgets = {
            'video_file': forms.FileInput(attrs={'accept': '.mov,video/quicktime'}),
        }
Flimm
  • 136,138
  • 45
  • 251
  • 267
4

There is no easy way to do this, you can see some good answers in this question Also, a personal suggestion (untested): after creating the form, set whatever attributes you want on it like this

    for f in form.fields:
        if isinstance(form.fields[f].widget, ClearableFileInput):
            form.fields[f].widget.attrs['accept'] = 'video/*'
Community
  • 1
  • 1
AdelaN
  • 3,366
  • 2
  • 25
  • 45
2

You can also do a simple step by including single line of code in you Form:

media = forms.FileField(widget=forms.FileInput(attrs={'accept':'image/*,video/*'}))

which sets the accept attribute on input element on the front-end of django. Note: this is also valid for forms.ImageField() also.

ARKhan
  • 1,724
  • 22
  • 30
1

Make a custom widget that takes an accept param

class AcceptingFileField(FileInput):
    def __init__(self, attrs=None, accept=['audio/*']):
        final_attrs = {}
        if accept:
            final_attrs = {'accept': ','.join(accept)}
        if attrs is not None:
            final_attrs.update(attrs)
        super(AcceptingFileField, self).__init__(attrs=final_attrs)

then you just go in your ModelForm

widgets = {
    'myvideoformfield': AcceptingFileField(accept=['video/*'])
}
CpILL
  • 6,169
  • 5
  • 38
  • 37