Package: django-s3-upload
django-s3-uploadCompatibilityThis library now supports Python3 and Django v1.11 and above only.Allows direct uploading of a file from the browser to AWS S3 via a file input field rendered by Django.The uploaded file's URL is then saveable as the value of that field in the database.This avoids the problem of uploads timing out when they go via a web server before being handed off to S3.Features include:displaying a progress barsupport for ACLs (eg, private uploads)support for encrypted-at-rest S3 bucketsmimetype and file extension whitelistingspecifying different bucket destinations on a per-field basisInstallationInstall with Pip:pip install django-s3-uploadAWS SetupAccess CredentialsYou have two options of providing access to AWS resources:Add credentials of an IAM user to your Django settings (see below)Use the EC2 instance profile and its attached IAM roleWhether you are using an IAM user or a role, there needs to be an IAM policy
in effect that grants permission to upload to S3:"Statement":[{"Effect":"Allow","Action":["s3:PutObject","s3:PutObjectAcl"],"Resource":"arn:aws:s3:::your-bucket-name/*"}]If the instance profile is to be used, the IAM role needs to have a
Trust Relationship configuration applied:"Statement":[{"Effect":"Allow","Principal":{"Service":"ec2.amazonaws.com"},"Action":"sts:AssumeRole"}]Note that in order to use the EC2 instance profile, django-s3-upload needs
to query the EC2 instance metadata using utility functions from thebotocore[] package. You already havebotocoreinstalled ifboto3is a dependency of your project.S3 CORSSetup a CORS policy on your S3 bucket.<CORSConfiguration><CORSRule><AllowedOrigin>http://yourdomain.com:8080</AllowedOrigin><AllowedMethod>POST</AllowedMethod><AllowedMethod>PUT</AllowedMethod><MaxAgeSeconds>3000</MaxAgeSeconds><AllowedHeader>*</AllowedHeader></CORSRule></CORSConfiguration>Django Setupsettings.pyINSTALLED_APPS=[...'s3upload',...]TEMPLATES=[{...'APP_DIRS':True,...}]# AWS# If these are not defined, the EC2 instance profile and IAM role are used.# This requires you to add boto3 (or botocore, which is a dependency of boto3)# to your project dependencies.AWS_ACCESS_KEY_ID=''AWS_SECRET_ACCESS_KEY=''AWS_STORAGE_BUCKET_NAME=''# The region of your bucket, more info:# http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_regionS3UPLOAD_REGION='us-east-1'# [Optional] Custom bucket endpoint url, with following keys (also optional):# region - region of your bucket# bucket - your bucket name# S3UPLOAD_BUCKET_ENDPOINT = 'https://{region}.non-amazon-s3-url.com/{bucket}'# Destinations, with the following keys:## key [required] Where to upload the file to, can be either:#     1. '/' = Upload to root with the original filename.#     2. 'some/path' = Upload to some/path with the original filename.#     3. functionName = Pass a function and create your own path/filename.# auth [optional] An ACL function to whether the current Django user can perform this action.# allowed [optional] List of allowed MIME types.# acl [optional] Give the object another ACL rather than 'public-read'.# cache_control [optional] Cache control headers, eg 'max-age=2592000'.# content_disposition [optional] Useful for sending files as attachments.# bucket [optional] Specify a different bucket for this particular object.# server_side_encryption [optional] Encryption headers for buckets that require it.S3UPLOAD_DESTINATIONS={'example_destination':{# REQUIRED'key':'uploads/images',# OPTIONAL'auth':lambdau:u.is_staff,# Default allow anybody to upload'allowed_types':['image/jpeg','image/png','video/mp4'],# Default allow all mime types'allowed_extensions':('.jpg','.jpeg','.png'),# Defaults to all extensions'bucket':'pdf-bucket',# Default is 'AWS_STORAGE_BUCKET_NAME''acl':'private',# Defaults to 'public-read''cache_control':'max-age=2592000',# Default no cache-control'content_disposition':'attachment',# Default no content disposition'content_length_range':(5000,20000000),# Default allow any size'server_side_encryption':'AES256',# Default no encryption}}urls.pyurlpatterns=[path(r'^s3upload/',include('s3upload.urls')),]Runpython manage.py collectstaticif required.Use in Django adminmodels.pyfromdjango.dbimportmodelsfroms3upload.fieldsimportS3UploadFieldclassExample(models.Model):video=S3UploadField(dest='example_destination')Use the widget in a custom formforms.pyfromdjangoimportformsfroms3upload.widgetsimportS3UploadWidgetclassS3UploadForm(forms.Form):images=forms.URLField(widget=S3UploadWidget(dest='example_destination'))*Optional.You can modify the HTML of the widget by overiding templates3upload/templates/s3upload-widget.tplviews.pyfromdjango.views.genericimportFormViewfrom.formsimportS3UploadFormclassMyView(FormView):template_name='form.html'form_class=S3UploadFormtemplates/form.html<html><head><metacharset="utf-8"><title>s3upload</title>{{ form.media }}</head><body><formaction=""method="post">{% csrf_token %}
        {{ form.as_p }}</form></body></html>ExamplesExamples of both approaches can be found in the examples folder. To run them:$gitclonegit@github.com:yunojuno/django-s3-upload.git
$cddjango-s3-upload# Add your AWS keys to your environmentexportAWS_ACCESS_KEY_ID='...'exportAWS_SECRET_ACCESS_KEY='...'exportAWS_STORAGE_BUCKET_NAME='...'exportS3UPLOAD_REGION='...'# e.g. 'eu-west-1'$docker-composeupVisithttp://localhost:8000/adminto view the admin widget andhttp://localhost:8000/formto view the custom form widget.