Skip to main content
cloud-upload

Django Attachments Framework

Django models, form fields, views, and Vue 3 components for file attachments, with direct-to-S3 uploads.

  • Attachment model: a concrete model with soft-delete, upload-completion tracking, size and content type.
  • HasAttachmentsMixin: adds an attachments many-to-many field to any model. ModelForms automatically render it with the upload widget.
  • Form fields: AttachmentsField (many) and AttachmentField (one), with file type, size, and count restrictions enforced in the browser and on submit.
  • Upload views: files go straight from the browser to S3 via presigned PUT URLs, or are streamed through Django for any other storage (e.g. FileSystemStorage in local development).
  • Google Drive import: users pick files from their Drive with the Google Picker, and a Celery job copies them into attachment storage (e.g. S3). Authentication reuses python-social-auth's Google login.
  • Background processors: Celery jobs that run after every upload (thumbnails, conversions, ...), with status tracking.
  • DRF serializer for attachments (swappable via settings).
  • Vue components (AttachmentManager, AttachmentUploader, AttachmentTable) and a headless useUploader composable. They depend only on Vue, and are styled with Bootstrap 5 classes.

Installation

The framework is published as two packages with the same name and version: the Django app on PyPI, and the Vue components on npm. Install the same version of both (see Versioning).

pip install django-attachments-framework  # depends on django-storages[s3]
pip install "django-attachments-framework[celery]"  # for background processors
pip install "django-attachments-framework[google]"  # for Google Drive import (includes Celery)

pnpm add django-attachments-framework  # or npm install; see "Frontend"
# settings.py
INSTALLED_APPS = [..., "attachments_framework"]

# urls.py
urlpatterns = [..., path("attachments/", include("attachments_framework.urls"))]

Then run python manage.py migrate.

Storage

Attachments use a storage alias from settings.STORAGES ("default" unless configured). When that storage is an S3Storage (from django-storages), uploads use presigned URLs. Use "signature_version": "s3v4", and allow PUT from your site's origin in the bucket's CORS configuration:

[{"AllowedOrigins": ["https://example.com"], "AllowedMethods": ["PUT"], "AllowedHeaders": ["content-type"]}]

Any other storage falls back to proxying the upload through Django.

Settings

All settings are optional:

ATTACHMENTS_FRAMEWORK = {
    "STORAGE": "default",                   # alias in settings.STORAGES (read once, at startup)
    "UPLOAD_TO": "attachments_framework.helpers.default_upload_to",  # (attachment, filename) -> path
    "UPLOAD_PREFIX": "",                    # e.g. "staging" -> staging/<attachment id>.pdf (default UPLOAD_TO only)
    "BACKEND": None,                        # dotted path to a BaseAttachmentBackend subclass; None = auto
    "PRESIGNED_URL_EXPIRATION": 3600,       # seconds
    "PERMISSION_CLASS": "attachments_framework.permissions.AttachmentPermission",
    "SERIALIZER": "attachments_framework.serializers.AttachmentSerializer",
    "MAX_FILE_SIZE": None,                  # bytes, enforced server-side for every upload
    "ALLOWED_FILE_TYPES": [],               # e.g. ["pdf", ".docx", "image/*"]

    # Background jobs (see "Background processors")
    "PROCESSORS": [],                       # dotted paths to AttachmentProcessor subclasses
    "CELERY_QUEUE": None,                   # None = Celery's default queue
    "JOB_MAX_RETRIES": 5,                   # retries after transient errors, with exponential backoff

    # Google Drive import (see "Google Drive import"); enabled when the API key and app id are set
    "GOOGLE_DRIVE_API_KEY": None,
    "GOOGLE_DRIVE_APP_ID": None,            # Google Cloud project number
    "GOOGLE_DRIVE_CREDENTIALS": "attachments_framework.google_drive.credentials.social_auth_access_token",
    "GOOGLE_DRIVE_SOCIAL_AUTH_BACKEND": "google-oauth2",
    "GOOGLE_DRIVE_AUTHORIZE_URL": None,     # None = python-social-auth's `social:begin` URL
    "GOOGLE_DRIVE_UPLOAD_TO": None,         # None = UPLOAD_TO
    "GOOGLE_DRIVE_REIMPORT": "new",         # or "reuse": return the user's existing attachment for a Drive file
    "GOOGLE_DRIVE_EXPORT_FORMATS": {...},   # how Google Docs/Sheets/Slides/Drawings are exported (docx/xlsx/pptx/png)
}

Permissions

The default AttachmentPermission requires login for everything. Any logged-in user may view and download attachments; only the uploader can finish an upload; only the uploader or staff can delete. Projects with multi-tenant data should subclass it:

from attachments_framework.permissions import AttachmentPermission

class OrgAttachmentPermission(AttachmentPermission):
    def has_object_permission(self, request, action, attachment):
        same_org = attachment.user.organization_id == request.user.organization_id
        return same_org and super().has_object_permission(request, action, attachment)

    def can_link(self, request, attachment, obj):
        return obj.organization_id == request.user.organization_id

Usage

Models

from attachments_framework.models import HasAttachmentsMixin

class Project(HasAttachmentsMixin):
    name = models.CharField(max_length=256)

project.attachments.add(attachment)
project.get_attachments()  # completed, non-deleted attachments

For a single attachment, use a regular ForeignKey(Attachment, ...) with AttachmentField in the form.

Besides the file itself (file, whose name is the storage path built by UPLOAD_TO), an attachment records where it came from: path is the folder the file was in, e.g. x/y/z/ (the relative path of a file in a folder selected in the uploader, or the file's folder in Google Drive when it is known), source is "upload" or "google_drive", and source_id/source_version identify the Drive file.

Forms

A ModelForm on a HasAttachmentsMixin model gets the upload widget for attachments automatically. To add restrictions, declare the field:

from attachments_framework.forms import AttachmentField, AttachmentsField

class ProjectForm(forms.ModelForm):
    attachments = AttachmentsField(required=False, max_number_of_files=5, max_file_size=20 * 1024 * 1024)
    cover_image = AttachmentField(required=False, allowed_file_types=["image/*"])

By default the widget only lists the attachments already selected; pass browse=True to list the whole queryset so users can choose from existing files. The widget renders an <attachment-manager> tag, so the form must sit inside a mounted Vue app (see below). While uploads are in progress, the component blocks form submission.

Templates

{% load attachments_framework %}

{# List an object's attachments; new uploads are linked to it when they finish #}
{% attachment_manager project max_file_size=1048576 %}

{# Or build the tag yourself #}
<attachment-manager
  :files="{{ attachments|attachments_json|jsonify }}"
  upload-start-url="{% url 'attachments_framework:upload_start' %}"
  :relations="{{ project|attachment_relations|jsonify }}"
></attachment-manager>

Pass google_drive=True to {% attachment_manager %}, AttachmentsField, or AttachmentField to add an "Import from Google Drive" button (once Google Drive import is set up, below).

relations maps model labels to primary keys ({"app.project": ["<pk>"]}). Only models using HasAttachmentsMixin can be targeted, and PERMISSION_CLASS.can_link is checked for each object.

Background processors

Processors run as Celery jobs after every completed upload, including imports. They require a Celery app that autodiscovers tasks from installed apps (app.autodiscover_tasks()) and a running worker.

from attachments_framework.processors import AttachmentProcessor, JobFailed, RetryableJobError

class ThumbnailProcessor(AttachmentProcessor):
    kind = "thumbnail"

    def applies_to(self, attachment):
        return attachment.content_type.startswith("image/")

    def run(self, attachment, job):
        ...  # raise RetryableJobError for transient failures, JobFailed(message) to fail with a message for users
        return {"thumbnail": key}  # stored as job.result

ATTACHMENTS_FRAMEWORK = {"PROCESSORS": ["myapp.processors.ThumbnailProcessor"]}

Each run is an AttachmentJob (attachment.jobs) with a status (pending, running, succeeded, failed), error, result, and attempts, visible in the admin and at jobs/<id>/ for the uploader. Jobs are sent to Celery when the surrounding transaction commits. To queue a job yourself, use attachments_framework.processors.enqueue_job(attachment, kind, params). Other code can also react to finished uploads through the attachments_framework.signals.upload_completed signal.

Google Drive import

Users pick one or more files from their Google Drive with the Google Picker. Each picked file becomes a pending Attachment, and a Celery job downloads it from Drive into the attachment storage (so with S3 configured, the file goes to S3). Google Docs, Sheets, Slides, and Drawings are exported as .docx, .xlsx, .pptx, and .png (GOOGLE_DRIVE_EXPORT_FORMATS). Google limits exports to 10 MB.

The import uses the drive.file scope, which Google classifies as non-sensitive, so your app doesn't need Google's restricted-scope security assessment. With this scope, the app can only access the files a user picks. As a result:

  • Folders cannot be imported, since picking a folder does not grant access to its contents. Users can open folders in the Picker and select the files inside them.
  • path is usually empty for imported files, because the app can't read the names of the folders around a file.

Imports are one-time copies: later changes in Drive are not synced.

Setup

  1. Install django-attachments-framework[google], set up python-social-auth's Google backend for sign-in, and run a Celery worker (see "Background processors").

  2. In the Google Cloud project that owns your OAuth client, enable the Google Drive API and the Google Picker API. Then create an API key, restricted to those two APIs and to your site's HTTP referrers. The Picker only works when the token, API key, and app ID all belong to the same project.

  3. Request the Drive scope and offline access from python-social-auth. Offline access provides a refresh token, so Celery workers can download files after the user's access token has expired:

    SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = ["https://www.googleapis.com/auth/drive.file"]
    SOCIAL_AUTH_GOOGLE_OAUTH2_AUTH_EXTRA_ARGUMENTS = {
        "access_type": "offline",
        # Google only returns a refresh token when the user consents; "consent" asks every time
        "prompt": "consent",
        "include_granted_scopes": "true",
    }
    

    Also add drive.file to the scopes of your OAuth consent screen.

  4. Configure the library:

    ATTACHMENTS_FRAMEWORK = {
        "GOOGLE_DRIVE_API_KEY": "AIza...",
        "GOOGLE_DRIVE_APP_ID": "123456789012",  # the project number, from the Cloud console dashboard
    }
    
  5. Enable the button with google_drive=True on the template tag or form field, or pass google-drive-config-url and google-drive-import-url to <attachment-manager>/<attachment-uploader> yourself.

Users who signed in before the Drive scope was added have tokens without it. When they click "Import from Google Drive", the config endpoint responds with an authorize_url, and the frontend sends them there to grant access. They are then returned to the page (customize this with the plugin's onGoogleAuthorizationRequired option). To get tokens some other way than python-social-auth, point GOOGLE_DRIVE_CREDENTIALS at a callable (user) -> access token that raises attachments_framework.google_drive.credentials.NeedsAuthorization when the user has to connect Google.

Re-importing

With GOOGLE_DRIVE_REIMPORT = "new" (the default), every import creates a new attachment. With "reuse", importing a Drive file that the same user already imported returns the existing attachment instead (it is still linked to the new relations). Reuse also covers an import that is still running. Deleted attachments and failed imports are never reused.

The global MAX_FILE_SIZE and ALLOWED_FILE_TYPES apply to imports, both when the import starts (using the Picker's metadata) and in the job (using Drive's metadata). Component and form field restrictions apply as they do to uploads.

Frontend

The Vue components are published to npm as django-attachments-framework, built as an ES module for your bundler (Vite, webpack, …). Vue ≥ 3.5 is a peer dependency, so the components use your project's copy of Vue:

pnpm add django-attachments-framework vue
// main.js
import { createApp } from "vue"
import AttachmentsFramework from "django-attachments-framework"

createApp({}).use(AttachmentsFramework, {
  // All optional:
  csrfToken: () => window.csrfmiddlewaretoken, // otherwise read from the page or the csrftoken cookie
  confirmDelete: file => window.confirm(`Delete ${file.name}?`), // null to skip confirmation
  concurrency: 3,
  jobPollInterval: 1500, // ms between status checks of imports
  onGoogleAuthorizationRequired: ({ authorizeUrl }) => window.location.assign(authorizeUrl),
  components: { AttachmentTable: MyAttachmentTable }, // swap out a component everywhere
}).mount("#app")

If you mount the app on Django-rendered DOM (as with the form widget), Vue has to compile templates in the browser, so alias vue to its full build:

// vite.config.js
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: [{ find: /^vue$/, replacement: "vue/dist/vue.esm-bundler.js" }],
  },
})

The package's few component styles are imported by its entry module, so they are bundled with your CSS. Extracting zips (the extractZips prop) uses @zip.js/zip.js, a dependency of the package that is imported dynamically: your bundler puts it in a separate chunk, which is only downloaded when a user adds the first zip. Google Drive import loads Google's Picker script (https://apis.google.com/js/api.js) when first used, so allow it in your Content Security Policy if you have one. The components use Bootstrap 5 classes, and Bootstrap Icons if they are loaded.

Versioning

The PyPI and npm packages are released together, always with the same version, so install matching versions (e.g. pin both in pyproject.toml/requirements.txt and package.json). Patch releases are compatible with each other; minor and major releases may change the protocol between the components and the Django views. The views report their version in an X-Attachments-Framework-Version header, and the components log a console warning when it isn't compatible with theirs (VERSION and isCompatibleVersion() are exported if you want to check it yourself).

Customizing

In increasing order of effort:

  1. Props: restrictions, columns, pageSize, searchThreshold, defaultSort, autoProceed, deletable, extractZips, …
  2. Slots: dropzone, item (an upload queue row), cell-<column key>, actions, empty. AttachmentManager forwards all of them.
  3. Replace a component through the plugin's components option, or compose AttachmentUploader and AttachmentTable yourself.
  4. Headless: build your own UI on useUploader(), which implements the upload protocol, the queue, progress, cancel/retry, and restrictions. filesFromDataTransfer(event.dataTransfer) expands dropped folders into { file, relativePath } entries to pass to addFiles(). expandZipFiles(files) replaces zips with the files inside them (extracted when their uploads start), skipping IGNORED_ARCHIVE_ENTRIES like __MACOSX/. useGoogleDrivePicker().open() resolves with picked Drive files to pass to addGoogleDriveFiles().
import { useUploader } from "django-attachments-framework"

const { items, addFiles, isBusy, totalProgress } = useUploader({
  uploadStartUrl: "/attachments/upload-start/",
  relations: { "app.project": projectId },
  onUploaded: attachment => files.value.push(attachment),
})

Upload protocol

  1. POST upload-start/ {name, size, content_type, path?} returns {attachment_id, upload: {method, url, headers}, complete_url}
  2. PUT the raw file to upload.url with upload.headers (a presigned S3 URL, or <id>/upload/ for proxied storage)
  3. POST complete_url {relations} returns the serialized attachment

Google Drive imports:

  1. GET google-drive/config/?next=<path> returns {access_token, api_key, app_id, export_formats} for the Picker, or 409 {error, authorize_url} when the user has to connect Google first
  2. POST google-drive/import/ {file: {id, name, mime_type, size}, relations} returns {attachment, job}. The attachment is linked to relations right away, but get_attachments() excludes it until the import completes.
  3. Poll GET job.status_url until status is succeeded (attachment is then completed) or failed (see error). job is null when an existing import was reused.

Other endpoints: <id>/view/ (inline), <id>/download/, <id>/delete/ (soft delete), jobs/<id>/ (job status).

Development

uv sync && uv run pytest     # Python tests
pnpm install && pnpm test    # Vue tests (vitest + jsdom)
pnpm build                   # build the npm package into frontend/dist (`pnpm build:watch` to rebuild on changes)

The Django app is in attachments_framework/, and the Vue sources are in frontend/. package.json holds the version of both packages (pyproject.toml reads it).

To work on both packages from a project that uses them, install them from your checkout:

# pyproject.toml (uv)
[tool.uv.sources]
django-attachments-framework = { path = "../django-attachments-framework", editable = true }
pnpm add django-attachments-framework@link:../django-attachments-framework

and run pnpm build:watch here. A linked package resolves its imports from this checkout's node_modules, which has its own copy of Vue (for the tests), so add resolve: { dedupe: ["vue"] } to the project's Vite config.

Releasing

pnpm version minor  # or patch/major: bumps package.json, commits, and tags v<version>
git push --follow-tags

The tag triggers .github/workflows/release.yml, which runs the tests and publishes both packages, using trusted publishing: add the repository and workflow as a trusted publisher on PyPI (environment pypi) and npm.

Metadata

Release files for django-attachments-framework 0.1.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-attachments-framework 0.1.0
File Size Uploaded Provenance Actions
django_attachments_framework-0.1.0.tar.gz 151.1 kB Without provenance Details for django_attachments_framework-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for django-attachments-framework 0.1.0
File Interpreter ABI Platform Actions
django_attachments_framework-0.1.0-py3-none-any.whl Python 3 none any Details for django_attachments_framework-0.1.0-py3-none-any.whl

Total release size: 196.4 kB

Release files / django_attachments_framework-0.1.0.tar.gz

Download URL django_attachments_framework-0.1.0.tar.gz
Size 151.1 kB
Tags Source
SHA-256 checksum
How to use checksums
0586ecaadc5d8b9cb3af17c985388f9183d8b032341190c9fc842ffe4a96b961
BLAKE2b-256 checksum
How to use checksums
5e4b33fe27beb149ea1254533ae5b15d88ef069fdc74c474966f2033584387d2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.11.28 {"installer":{"name":"uv","version":"0.11.28","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / django_attachments_framework-0.1.0-py3-none-any.whl

Download URL django_attachments_framework-0.1.0-py3-none-any.whl
Size 45.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d70ca5929d135c4945f83180aaef2709a128b84abc7a043806a5f8943f1a7f8d
BLAKE2b-256 checksum
How to use checksums
fdf1ddb4c58683987fbb0d7bd592d0adadc8bf2774f48d489c8bc1d99745d4dd
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.11.28 {"installer":{"name":"uv","version":"0.11.28","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for django-attachments-framework 0.1.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.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

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