Skip to content

Commit

Permalink
Merge pull request #46 from Formulka/ValidateContentTypeFromExtension
Browse files Browse the repository at this point in the history
AllowedContentTypesFileValidator validates content_type from both extension and content
  • Loading branch information
matllubos committed May 29, 2017
2 parents d67ceb9 + c42abdc commit 7d66301
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 5 deletions.
13 changes: 9 additions & 4 deletions chamber/models/fields.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import unicode_literals

import mimetypes
import os
from decimal import Decimal
from uuid import uuid4 as uuid
Expand Down Expand Up @@ -75,13 +76,17 @@ def __init__(self, content_types):
self.content_types = content_types

def __call__(self, data):
extension_mime_type = mimetypes.guess_type(data.file.name)[0]
mime_type = None
with magic.Magic(flags=magic.MAGIC_MIME_TYPE) as m:
mime_type = m.id_buffer(data.file.read(1024))
data.file.seek(0)
if mime_type not in self.content_types:
raise ValidationError(
ugettext('Unsupported file type')
)

if not {extension_mime_type, mime_type} <= set(self.content_types):
raise ValidationError(
ugettext('Unsupported file type')
)

return data


Expand Down
2 changes: 1 addition & 1 deletion example/dj/apps/test_chamber/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ class TestFieldsModel(chamber_models.SmartModel):
state_graph = chamber_models.EnumSequencePositiveIntegerField(verbose_name=_('graph'), null=True, blank=True,
enum=GRAPH)
file = chamber_models.FileField(verbose_name=_('file'), null=True, blank=True,
allowed_content_types=('application/pdf', 'text/plain'))
allowed_content_types=('application/pdf', 'text/plain', 'text/csv'))
image = chamber_models.FileField(verbose_name=_('image'), null=True, blank=True, max_upload_size=1)
price = chamber_models.PriceField(verbose_name=_('price'), null=True, blank=True, currency=_('EUR'))
total_price = chamber_models.PositivePriceField(verbose_name=_('total price'), null=True, blank=True)
Expand Down

0 comments on commit 7d66301

Please sign in to comment.