multifile.py 3.24 KB
Newer Older
stef's avatar
stef committed
1
2
3
4
5
6
7
8
"""
A newforms widget and field to allow multiple file uploads.

Created by Edward Dale (www.scompt.com)
Released into the Public Domain
"""

from django.utils.encoding import force_unicode
Okhin's avatar
Okhin committed
9
from django.utils.datastructures import MultiValueDict, MergeDict
stef's avatar
stef committed
10
11
12
from django.utils.translation import ugettext
from django.forms.fields import Field, EMPTY_VALUES
from django.core.files.uploadedfile import UploadedFile
Okhin's avatar
Okhin committed
13
from django.forms.widgets import Input, FILE_INPUT_CONTRADICTION
stef's avatar
stef committed
14
from django.forms.util import ErrorList, ValidationError, flatatt
stef's avatar
stef committed
15
from django.utils.safestring import mark_safe
stef's avatar
stef committed
16

Okhin's avatar
Okhin committed
17
18
19
FILE_INPUT_EMPTY_VALUE = object()

class MultiFileInput(Input):
stef's avatar
stef committed
20
21
22
23
    """
    A widget to be used by the MultiFileField to allow the user to upload
    multiple files at one time.
    """
Okhin's avatar
Okhin committed
24
25
    input_type = 'file'
    needs_multipart_form = True
stef's avatar
stef committed
26
27
28
29
30
31
32

    def render(self, name, value, attrs=None):
        """
        Renders the MultiFileInput.
        Should not be overridden.  Instead, subclasses should override the
        js, link, and/or fields methods which provide content to this method.
        """
Okhin's avatar
Okhin committed
33
34
        if attrs is None:
            attrs = {}
stef's avatar
stef committed
35

Okhin's avatar
Okhin committed
36
37
        name += '[]'
        attrs['multiple'] = 'multiple'
stef's avatar
stef committed
38

Okhin's avatar
Okhin committed
39
        return super(MultiFileInput, self).render(name, None, attrs=attrs)
stef's avatar
stef committed
40
41
42

    def value_from_datadict(self, data, files, name):
        """
Okhin's avatar
Okhin committed
43
44
        File widget takes data from FILES, not POST
        we need to add [] for w3c recoomendation
stef's avatar
stef committed
45
        """
Okhin's avatar
Okhin committed
46
47
        name += '[]'
        if isinstance(files, (MultiValueDict, MergeDict)):
stef's avatar
stef committed
48
            return files.getlist(name)
Okhin's avatar
Okhin committed
49
        return files.get(name, None)
stef's avatar
stef committed
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64

    def id_for_label(self, id_):
        """
        The first file input box always has a 0 appended to it's id.
        """
        if id_:
            id_ += '0'
        return id_
    id_for_label = classmethod(id_for_label)

class MultiFileField(Field):
    """
    A field allowing users to upload multiple files at once.
    """
    widget = MultiFileInput
Okhin's avatar
Okhin committed
65
66
    max_length = None
    allow_empty_file = None
stef's avatar
stef committed
67

Okhin's avatar
Okhin committed
68
    def to_python(self, data):
stef's avatar
stef committed
69
70
71
72
        """
        Cleans the data and makes sure that all the files had some content.
        Also checks whether a file was required.
        """
Okhin's avatar
Okhin committed
73
        if data in EMPTY_VALUES:
stef's avatar
stef committed
74
            return None
Okhin's avatar
Okhin committed
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
        if data is FILE_INPUT_EMPTY_VALUE:
            raise validationError(self.Error_messages['empty_multiply'])

        # UploadedFile objects should have name and size attributes
        for d in data:
            try:
                file_name = d.name
                file_size = d.size
            except AttributeError:
                raise ValidationError(self.Error_messages['invalid'])

            if self.max_length is not None and file_size > self.max_length:
                error_values = {'max': self.max_length, 'length': file_size}
                raise ValidationError(self.error_messages['max_length'] % error_values)
            if not file_name:
                raise ValidationError(self.error_messages['invalid'])
            if not self.allow_empty_file and not file_size:
                raise ValidationError(self.Error_messages['empty'])
        return data

    def bound_data(self, data, initial):
        if data in (None, FILE_INPUT_EMPTY_VALUE, FILE_INPUT_CONTRADICTION):
            return initial
        return data