Package: django-simple-file-handler
The django-simple-file-handler Django app uploads and manages documents and images. It is most useful when used to add these functions to your own apps, and it can also be used to add image processing and PDF generation from HTML templates.Please note that “private” files and PDFs would be more accurately described as “hidden.” The app generates a proxy URL that will load the file for a logged-in user and stores the file with a name consisting of many random characters. Still, it is possible to load these files without logging in if the file path is known.Quick startRunpip installdjango-simple-file-handler.Add django-simple-file-handler to your installed apps:INSTALLED_APPS = (
    ...
    'django_simple_file_handler',
)Runpython manage.py migrate.Include the django-simple-file-handler URLconf in your project urls.py like this (this step is only required if you wish to use private files or PDFs):urlpatterns = [
    ...
    path(
        'private-file-pseudo-directory-path/',
        include('django_simple_file_handler.urls'),
    ),
]BasicsPublic and private document objects, as well as unprocessed image objects, can be created and managed via the admin site. Other types are read-only in the admin site.All types can be created and accessed by subclassing or creating a foreign key in your own apps.Temporary documents and temporary PDFs are intended to be used when two or more objects might need to have the same title. These add a string of random characters to the ends of file names to prevent overwriting files.ClassesPublicDocument— Includes uploaded document filePrivateDocument— Includes uploaded document file with a proxy URL requiring loginTemporaryDocument—  Includes uploaded document file with a modified file name allowing title duplicationUnprocessedImage— Includes uploaded image fileProcessedImage— Includes uploaded image file and processed image filePublicPDF— Includes generated PDF filePrivatePDF— Includes generated PDF file with a proxy URL requiring loginTemporaryPDF— Includes generated PDF file with a modified file name allowing title duplicationAttributescreated—DateTimeFieldwith automatically generated valueupdated—DateTimeFieldwith automatically generated valuetitle—CharFieldwithmax_lengthof 245 characters (not available forProcessedImage)extra_text—TextField(optional)saved_file—FileFieldfor the uploaded fileprocessed_file—FileFieldfor processed image (ProcessedImageonly)output_width—PositiveIntegerFieldfor processed image width in pixels (ProcessedImageonly)output_height—PositiveIntegerFieldfor processed image height in pixels (ProcessedImageonly)Methodsfile_url— Returns URL of the uploaded file as a stringfile_link— Returns an HTML link to the URL of the uploaded file as a stringproxy_url— Returns proxy URL for the uploaded file as a string (PrivateDocumentandPrivatePDFonly)proxy_link— Returns an HTML link to the proxy URL for the uploaded file as a string (PrivateDocumentandPrivatePDFonly)image_url— Returns URL of the processed image file as a string (ProcessedImageonly)image_link— Returns  an HTML link to the URL of the processed image file as a string (ProcessedImageonly)image_height— Returns an integer for the height of the processed image in pixels. (ProcessedImageonly)image_width— Returns an integer for the width of the processed image in pixels. (ProcessedImageonly)saved_file_height— Returns an integer for the height of the source image in pixels. (ProcessedImageonly)saved_file_width— Returns an integer for the width of the source image in pixels. (ProcessedImageonly)Processed imagesRefer to thePillowdocumentation for allowed import formats or see the section below on file types to limit them in your forms.Images are processed when an instance is saved with a file assigned to thesaved_filefield and a value for one or both of theoutput_widthandoutput_heightfields. If one value is given, the image will be scaled proportionally. If both are supplied and they do not match the proportions of the source image, the image will be scaled and cropped on either the bottom or right side, depending on whether the source image is horizontal or vertical.The processed image is stored in theprocessed_filefield, while the original file assigned tosaved_fileis unchanged and can be processed again as needed. Refer to the attributes and methods list above for additional information.By default, images are processed into PNGs with RGBA mode. To change one or more of the output parameters, add aFILE_HANDLER_PILLOWsetting with a dictionary containing parameters you wish to change, as in this example:FILE_HANDLER_PILLOW = {
    'output_mode': 'P',
    'content_type': 'image/gif',
    'file_format': 'GIF',
    'file_extension': 'gif',
}Refer to Pillow documentation for options for these parameters.Generating PDFsPDF generation will useWeasyPrintif it is installed andFILE_HANDLER_WEASYPRINT = Trueis present in Django settings. Otherwise, it will usexhtml2pdf, which wil be installed if not present. This app has been tested with WeasyPrint 0.28. Please refer to xhtml2pdf or WeasyPrint documentation for HTML template-formatting specifics.The example code below usesPublicPDF, butPrivatePDFandTemporaryPDFwork the same way.generated_pdf = PublicPDF.objects.create(
    title='title of the generated PDF document',
    extra_text='any additional text needed with the object',
    template_location='path/to/your/html/template.html',
    template_data={
        'value_one': value_to_be_inserted_in_template,
        'value_two': value_to_be_inserted_in_template,
        'value_three': value_to_be_inserted_in_template,
    },
)Database object attributes can then be changed without rewriting the PDF file. The file is only written when thetemplate_datadictionary is given and the object is resaved.File formatsIfpython-magicis installed, django-simple-file-handler will use it to check uploaded file MIME types. Otherwise, it will use Python’s built-in library. This package has been tested with python-magic 0.4.Supported document formats include PDF, ZIP, Word, Excel and PowerPoint. Supported unprocessed image formats include PNG, JPEG and GIF.To support different file types, follow this example for your form:class MyForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['saved_file'].validators.append(CheckExtMIME(allowed_attributes=MY_DICTIONARY))

    class Meta:
        model = PublicDocument
        fields = [
            'title',
            'extra_text',
            'saved_file',
        ]The dictionary’s format can optionally include keys with list values for file extensions, MIME types and verbose names for file formats (these will appear in error messages if given). Here is an example:MY_DICTIONARY = {
    'allowed_extensions' : [
        'abc',
        'def',
        'ghi',
    ],
    'allowed_mimetypes' : [
        'application/example1',
        'application/example2',
        'image/example3',
    ],
    'allowed_verbose' : [
        'Format1',
        'Format2',
        'Format3',
    ],
}Dictionaries included indjango_simple_file_handler.file_typesinclude:CHECK_DOC— Allows ZIP, Word, Excel and PowerPoint.CHECK_WEB_IMAGE— Allows GIF, JPEG and PNG.CHECK_RAW_IMAGE— Allows GIF, JPEG, PNG and TIFF.CHECK_PDF— Allows PDF only.CHECK_ALL_WEB— Allows GIF, JPEG, PNG ZIP, Word, Excel and PowerPoint.File locationsBy default, images will be stored in yourmediadirectory in subdirectories nameddocuments,imagesandpdf. If you wish to change the directory where these subdirectories are created, addFILE_HANDLER_DIRECTORY = 'path/to/location/'to your settings.Advanced useThe django-simple-file-handler models and admin classes make use of modular, reusable mixins and functions that can, of course, be imported for use with your own code.