Skip to main content

Python Django License PyPIv PyPIs Build Status Coverage Status Downloads

ConstrainedFileField for Django

This 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.

Features

  • File size limitation

  • File type limitation

  • Javascript file size checker

Requirements

  • Python >= 3.5

  • Django>= 2.2.28

  • python-magic >= 0.4.2 iff you want to check the file type

Installation

Using PyPI

  1. Run

    • pip install django-constrainedfilefield, or

    • pip install django-constrainedfilefield[filetype] to ensure python-magic is installed.

  2. For windows, you must download the dll files and .magic file at https://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#dependencies

Using the source code

  1. Make sure Pandoc is installed

  2. Run ./pypi_packager.sh

  3. Run pip install dist/django_constrainedfilefield-x.y.z-[...].wheel, where x.y.z must be replaced by the actual version number and [...] depends on your packaging configuration

  4. For windows, you must download the dll files and .magic file at https://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#dependencies

Usage

Validate single file

The field can be used in forms or model forms like a normal FileField. 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 (on save()), but when validated through a form.

Creating form from model

Create a model and add a field of type ConstrainedFileField. 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 regular FileField.

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 form

from 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 validation

Additionally, to prevent user uploading too large files, a javascript checker can be set to the form field. In order to achieve that, you need to

  1. Add constrainedfilefield to the INSTALLED_APPS. This will load the javascripts from the static files.

  2. Activate this feature by setting js_checker=True when instantiating the ConstrainedFileField.

  3. Include the javascript in the template where the form field is used

    {% load static %}
    <script src="{% static 'constrainedfilefield/js/file_checker.js' %}"></script>

Validate single image

Same as above, using ConstrainedImageFileField instead.

The ConstrainedImageField offers additional constraints: * [min|max]_upload_[width|height] to define min/max dimensions, respectively width and height.

Note on DOS attacks

Important 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 use LimitRequestBody directive.

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 give max_upload_size a small value (e.g. 5Mb) and LimitRequestBody a higher one (e.g. 100Mb).

Credits

This is a fork of django-validated-file from Kaleidos.

Metadata

Release files for django-constrainedfilefield 5.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-constrainedfilefield 5.0.0
File Size Uploaded Provenance
django-constrainedfilefield-5.0.0.tar.gz 18.9 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for django-constrainedfilefield 5.0.0
File Interpreter ABI Platform
django_constrainedfilefield-5.0.0-py3-none-any.whl Python 3 none any Details

Total release size: 40.5 kB

Release files / django-constrainedfilefield-5.0.0.tar.gz

Download URL django-constrainedfilefield-5.0.0.tar.gz
Size 18.9 kB
Tags Source
SHA-256 checksum
How to use checksums
ecb1835602ecf45eeb7cd8eb0ef2e0a7179be07c2d9eb2031a1f4392da975d4c
BLAKE2b-256 checksum
How to use checksums
5a1e3a1227b15ae11b15bcf7410f3e8bc8522a202a4cf13ea0e7c413de5f277c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.1 CPython/3.9.5

Release files / django_constrainedfilefield-5.0.0-py3-none-any.whl

Download URL django_constrainedfilefield-5.0.0-py3-none-any.whl
Size 21.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
53e39ebca0a12b145d21ace25b78eb67d8e16109acc293af4d99805b32beb197
BLAKE2b-256 checksum
How to use checksums
c57ae6c4fd30bdb047b521fdbf214f1294ad86c18bec465493ad74d4bd9432dc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.1 CPython/3.9.5

Security for django-constrainedfilefield 5.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page