-
Notifications
You must be signed in to change notification settings - Fork 1
/
general_form.py
94 lines (75 loc) · 2.81 KB
/
general_form.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
"""
General functions, mostly used in forms (forms.py)
"""
from django import forms
from django.conf import settings
from django.forms import ValidationError
from projects.models import ProjectImage
from templates import widgets
def clean_file_default(self, required=True):
"""
A check for an uploaded file. Checks filesize.
:param self:
:param required: Whether it is required to have a file.
:return:
"""
file = self.cleaned_data.get("File")
if file:
s = file.size
if s > settings.MAX_UPLOAD_SIZE:
raise ValidationError(
"The file is too large, it has to be at most " + str(
round(settings.MAX_UPLOAD_SIZE / 1024 / 1024)) + "MB and is " + str(
round(s / 1024 / 1024)) + "MB.")
elif required:
raise ValidationError("No file supplied!")
return file
class FileForm(forms.ModelForm):
"""
A form to upload a file. It has a filefield and a caption field. More fields can be added.
"""
class Meta:
model = ProjectImage # when inherited, this model can be overwritten. ProjectImage is only used as default.
fields = ['Caption', 'File']
widgets = {
'Caption': widgets.MetroTextInput,
'File': widgets.MetroFileInput
}
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super().__init__(*args, **kwargs)
def clean_File(self):
"""
:return:
"""
return clean_file_default(self)
def save(self, commit=True):
"""
:param commit:
:return:
"""
instance = super().save(commit=False)
if 'File' in self.changed_data:
instance.OriginalName = instance.File.name
if commit:
instance.save()
return instance
class ConfirmForm(forms.Form):
"""Form to confirm a action. Used for extra validation. Not linked to a model."""
confirm = forms.BooleanField(widget=widgets.MetroCheckBox, label='Confirm:')
class CsvUpload(forms.Form):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# show only csv in file selection dialog
self.fields['csvfile'].widget.attrs['accept'] = '.csv'
csvfile = forms.FileField(widget=widgets.MetroFileInput)
delimiter = forms.ChoiceField(widget=widgets.MetroSelect, choices=(
(',', ','),
(';', ';')
))
def clean_csvfile(self):
file = self.cleaned_data.get("csvfile")
if not file:
raise ValidationError("No file supplied!")
if file.content_type != 'text/csv' and file.content_type != 'application/vnd.ms-excel':
raise ValidationError("Not a csv file!")