Routeur: Ajout temporaire des modules workflow et dae en écriture
[auf_rh_dae.git] / src / auf.django.emploi / auf / django / emploi / fields.py
CommitLineData
ab72a5f9
OL
1# -*- coding: utf-8 -*-
2
3from django.db.models import FileField
4from django.forms import forms
5from django.template.defaultfilters import filesizeformat
6from django.utils.translation import ugettext_lazy as _
7
8class ContentTypeRestrictedFileField(FileField):
9 """
10 Same as FileField, but you can specify:
11 * content_types - list containing allowed content_types. Example: ['application/pdf', 'image/jpeg']
12 * max_upload_size - a number indicating the maximum file size allowed for upload.
13 2.5MB - 2621440
14 5MB - 5242880
15 10MB - 10485760
16 20MB - 20971520
17 50MB - 5242880
18 100MB 104857600
19 250MB - 214958080
20 500MB - 429916160
21"""
22 def __init__(self, *args, **kwargs):
23 self.content_types = kwargs.pop("content_types")
24 self.max_upload_size = kwargs.pop("max_upload_size")
25
26 super(ContentTypeRestrictedFileField, self).__init__(*args, **kwargs)
27
28 def clean(self, *args, **kwargs):
29 data = super(ContentTypeRestrictedFileField, self).clean(*args, **kwargs)
30
31 file = data.file
32 try:
33 params = {
34 'max': filesizeformat(self.max_upload_size),
35 'current': filesizeformat(file._size),
36 'allowed': ", ".join(self.content_types),
37 }
38 content_type = file.content_type
39 if content_type in self.content_types:
40 if file._size > self.max_upload_size:
41 msgid = 'Please keep filesize under %(max)s. Current filesize %(current)s'
42 raise forms.ValidationError(_(msgid) % params)
43 else:
44 msgid = "Filetype not supported. (allowed: %(allowed)s"
45 raise forms.ValidationError(_(msgid) % params)
46 except AttributeError:
47 pass
48
49 return data