Package: django-constrainedfilefield
ConstrainedFileField for DjangoThis Django app adds a new field type,ConstrainedFileField, that
has the capability of checking the file size and type. Also provides a
javascript checker for the form field.FeaturesFile size limitationFile type limitationJavascript file size checkerRequirementsPython>= 3.5Django>= 2.2.28python-magic>= 0.4.2iffyou want to check the file typeInstallationUsing PyPIRunpip installdjango-constrainedfilefield, orpip installdjango-constrainedfilefield[filetype]to ensurepython-magicis installed.For windows, you must download the dll files and .magic file athttps://github.com/pidydx/libmagicwin64(32-bit version:http://gnuwin32.sourceforge.net/packages/file.htm)), add them to
C:WindowsSystem32 (or to a folder in your PATH), and set
MAGIC_FILE_PATH=“…” to the path of your .magic file in your
settings.py. For more information about the files to download, go to:
https://github.com/ahupp/python-magic/blob/43df08c5ed63d7aad839695f311ca1be2eeb1ecb/README.md#dependenciesUsing the source codeMake surePandocis installedRun./pypi_packager.shRunpip installdist/django_constrainedfilefield-x.y.z-[...].wheel,
wherex.y.zmust be replaced by the actual version number and[...]depends on your packaging configurationFor windows, you must download the dll files and .magic file athttps://github.com/pidydx/libmagicwin64(32-bit version:http://gnuwin32.sourceforge.net/packages/file.htm)), add them to
C:WindowsSystem32 (or to a folder in your PATH), and set
MAGIC_FILE_PATH=“…” to the path of your .magic file in your
settings.py. For more information about the files to download, go to:
https://github.com/ahupp/python-magic/blob/43df08c5ed63d7aad839695f311ca1be2eeb1ecb/README.md#dependenciesUsageValidate single fileThe field can be used in forms or model forms like a normalFileField. If a user tries to upload a file which is too large or
without a valid type, a form validation error will occur.Note that the validation does not occur on the field itself (onsave()), but when validated through a form.Creating form from modelCreate a model and add a field of typeConstrainedFileField. You can
add a maximum size in bytes and a list of valid mime types that will be
allowed. The list of all mime types is available here:http://www.iana.org/assignments/media-types/index.html. Setting none of
the above, it behaves like a regularFileField.from django.db import models
from constrainedfilefield.fields import ConstrainedFileField

class TestModel(models.Model):
    the_file = ConstrainedFileField(
                            null=True,
                            blank=True,
                            upload_to='testfile',
                            content_types=['image/png'],
                            max_upload_size=10240
                                    )from django import forms
from myproject.models import TestModel

class TestModelForm(forms.ModelForm):
    class Meta:
        model = TestModel
        fields = ['the_file']Building a formfrom django import forms
from constrainedfilefield.fields import ConstrainedFileField

class TestNoModelForm(forms.Form):
    the_file = ConstrainedFileField(
                            null=True,
                            blank=True,
                            upload_to='testfile',
                            content_types=['image/png'],
                            max_upload_size=10240
                                    ).formfield()Javascript file size validationAdditionally, to prevent user uploading too large files, a javascript
checker can be set to the form field. In order to achieve that, you need
toAddconstrainedfilefieldto theINSTALLED_APPS. This will
load the javascripts from the static files.Activate this feature by settingjs_checker=Truewhen
instantiating theConstrainedFileField.Include the javascript in the template where the form field is used{%loadstatic%}<script src="{%static'constrainedfilefield/js/file_checker.js'%}"></script>Validate single imageSame as above, usingConstrainedImageFileFieldinstead.TheConstrainedImageFieldoffers additional constraints: *[min|max]_upload_[width|height]to define min/max dimensions,
respectively width and height.Note on DOS attacksImportant note: the check of the file size is made by Django once the
whole file has been uploaded to the server and stored in a temp
directory (or in memory if the file is small). Thus, this is useful to
guarantee the quota of the users, for example, but will not stop an
attacking user that wants to block the server by sending huge files (e.
g. of several Gb).To avoid this, you need to configure your front end to limit the size of
uploaded files. How to do it depends on the software you are using. For
example, if you use apache, you should useLimitRequestBodydirective.This is a complementary measure, because you’ll usually want normal
users that exceed the size by a reasonable amount to get a friendly form
validation message, while attacking users will see how their connection
is abruptly cut before the file finishes uploading. So the recommended
setting is to givemax_upload_sizea small value (e.g. 5Mb) andLimitRequestBodya higher one (e.g. 100Mb).CreditsThis is a fork ofdjango-validated-filefromKaleidos.