@@ -11,8 +11,8 @@ Installation
11
11
* Note that this package depends on python-magic (to check field types).
12
12
* Add 'validatedfile' to your INSTALLED_APPS in settings.py.
13
13
14
- Usage
15
- -----
14
+ Validate single file
15
+ --------------------
16
16
17
17
Create a model and add a field of type ValidatedFileField. You can add a maximum size in bytes
18
18
and a list of valid mime types that will be allowed. The list of all mime types is available
@@ -33,6 +33,62 @@ The model can be used in forms or model forms like a normal FileField. If a user
33
33
a file with too much size or without a valid type, a form validation error will occur.
34
34
35
35
36
+ Validate quota usage
37
+ --------------------
38
+
39
+ This example also checks the total size of all files uploaded by one user::
40
+
41
+ (in models.py)
42
+
43
+ from django.contrib.auth.models import User
44
+ from django.db import models
45
+ from validatedfile.models import ValidatedFileField
46
+
47
+ class TestModel(models.Model):
48
+ user = models.ForeignKey(
49
+ User,
50
+ null = False,
51
+ blank = False,
52
+ related_name = 'test_models')
53
+ the_file = ValidatedFileField(
54
+ null = True,
55
+ blank = True,
56
+ upload_to = 'testfile',
57
+ max_upload_size = 10240,
58
+ content_types = ['image/png'])
59
+
60
+ (in forms.py)
61
+
62
+ from django import forms
63
+ from validatedfile.models import QuotaValidator
64
+ from models.py import TestModel
65
+
66
+ class TestModelForm(models.ModelForm):
67
+ the_file = forms.FileField(
68
+ required = True,
69
+ validators = [QuotaValidator(max_usage = 102400)])
70
+
71
+ class Meta:
72
+ model = TestModel
73
+ fields = ['the_file']
74
+
75
+ def __init__(self, user, *args, **kwargs):
76
+ super(TestModelForm, self).__init__(*args, **kwargs)
77
+ self.user = user
78
+ self.fields['the_file'].validators[0].update_quota(
79
+ items = self.user.test_models.all(),
80
+ attr_name = 'the_file',
81
+ )
82
+
83
+ def exceeds_quota(self):
84
+ return self.fields['the_file'].validators[0].quota.exceeds()
85
+
86
+ def save(self, *args, **kwargs):
87
+ model = super(TestModelForm, self).save(commit = False)
88
+ model.user = self.user
89
+ model.save()
90
+
91
+
36
92
Note on DOS attacks
37
93
-------------------
38
94
0 commit comments