Skip to content

Commit b83fa66

Browse files
committed
Document more
1 parent d9be067 commit b83fa66

File tree

2 files changed

+59
-3
lines changed

2 files changed

+59
-3
lines changed

README.rst

Lines changed: 58 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@ Installation
1111
* Note that this package depends on python-magic (to check field types).
1212
* Add 'validatedfile' to your INSTALLED_APPS in settings.py.
1313

14-
Usage
15-
-----
14+
Validate single file
15+
--------------------
1616

1717
Create a model and add a field of type ValidatedFileField. You can add a maximum size in bytes
1818
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
3333
a file with too much size or without a valid type, a form validation error will occur.
3434

3535

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+
3692
Note on DOS attacks
3793
-------------------
3894

validatedfile/tests/models.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from django.db import models
2-
from validatedfile.models import ValidatedFileField, QuotaValidator
2+
from validatedfile.models import ValidatedFileField
33

44
class TestModel(models.Model):
55
the_file = ValidatedFileField(

0 commit comments

Comments
 (0)