A generic set of template tags to attach files to specific models.
Project description
django-nifty-attachments
Version: 0.2.0
"Private" file attachments for a Django Model, with permissions-based access control and without Generic FK.
This package is a re-write of django-attachments, originally developed by atadorov.
django-nifty-attachmentsis free software distributed under the MIT License.
Adaptations:
Re-wrote app top-to-bottom to accommodate strict access control and remove Generic FK, among others.
- Removed support for python2 & django<3, delete migrations, delete locale, delete admin, delete management command
- Remove Generic FK to "related object" , replace with "Model Factory" pattern, using Abstract Model and dependency inversion instead.
- Provide injectable permissions with access control for private files
- Implement "app settings" pattern
Installation:
-
Put
nifty_attachmentsto yourINSTALLED_APPSin yoursettings.pywithin your django project (to auto-detect templates and tags):INSTALLED_APPS = ( ... 'nifty_attachments', ) -
Define a concrete Attachment model with relation to your related object:
class GizmoAttachment(AbstractAttachment.factory("myapp.Gizmo")): """ A concrete implementation of AbstractAttachment, with a required FK named `related` to Gizmo with reverse relation "attachment_set" """ -
Add the attachments urlpattern to your
urls.py, injecting your concrete attachment model:path(r'^gizmo/attachments/', include('attachments.urls', namespace='gizmo-attachments', kwargs=dict(model='myapp.GizmoAttachment')), -
Migrate your database:
./manage.py migrate -
Grant the user some permissions:
-
For viewing / downloading attachments grant the user (or group) the permission
gizmo.view_attachment. -
For adding attachments grant the user (or group) the permission
gizmo.add_attachment. -
For updating attachments grant the user (or group) the permission
gizmo.change_attachment. -
For deleting own attachments grant the user (or group) the permission
gizmo.delete_attachment. This allows the user to delete their own attachments only. -
For updating or deleting any attachments (including attachments by other users) grant the user the permission
gizmo.edit_any_attachment.
-
Settings
-
ATTACHMENTS_FILE_UPLOAD_MAX_SIZEThe maximum upload file size in Mb. Default:10 Mb. Set toNonefor no restriction on file size. -
ATTACHMENTS_CONTENT_TYPE_WHITELISTA tuple of http content type strings to allow for upload. Default:(). Set to()for no restriction on content type.
Configuration
-
configure file upload validators:
- define an iterable of
Callable[[File], ]; Validators execute against uploadedFile. Raise aValidationErrorto deny the upload. - configure setting
ATTACHMENTS_FILE_UPLOAD_VALIDATORSequal to the iterable or a dotted path to it. E.g.ATTACHMENTS_FILE_UPLOAD_VALIDATORS = "attachments.validators.default_validators" - For custom validators on different Concrete Attachment types, inject custom
form_classto add view.
- define an iterable of
-
configure permissions: implement the interface defined by
AttachmentPermissionsApiand setpermissions = MyAttachmentsPermissions()on your concrete Attachment Model.
Usage:
In your models:
You must explicitly define a Concrete Attachments model for each related model.
-
use the
factorymethod onAbstractAttachmentto create a base model with a FK to yourrelated_model -
extend this abstract base class, you can add or override any behaviours you like.
-
if you provide a custom
Metaoptions, it is highly recommended you extend the base Meta.base_model = AbstractAttachment.factory("myapp.Gizmo") class GizmoAttachment(base_model): ... class Meta(base_model.Meta) ... -
You can also inject custom permissions logic with any class that implements
AttachmentPermissionsProtocol.class GizmoPermissions(DefaultAttachmentPermissions): def can_add_attachments(self, user: User, related_to: "Gizmo") -> bool: """ Return True iff the user can upload new attachments to the given Gizmo """ return gizmo.permissions.can_change(user, related_to) and super().can_add_attachments(user, related_to) base_model = AbstractAttachment.factory( related_model = "myapp.Gizmo", permissions_class = GizmoPermissions ) class GizmoAttachment(base_model): ...
In your urls:
You need one namespaced set of attachment urls for each concrete Model.
-
Include the
attachments.urls, supplying an explicit namespace if your app urls are not namespaced. -
Inject your concrete Attachment Model, either the Model class or an
app_label.ModelNamestring.path('gizmo/attachments/', include('attachments.urls', namespace='gizmo-attachments'), kwargs=dict(model='myapp.GizmoAttachment')),
To use distinct templates for a specific concrete Attachment type, either
-
copy in a url from
attachments.urls, adding atemplate_namekwarg, to customize an individual view; or -
add at
template_prefixkwarg to the path include with a template path prefix.path('gizmo/attachments/', include('attachments.urls', namespace='gizmo-attachments'), kwargs=dict(model='myapp.GizmoAttachment', template_prefix='gizmo/')),
Also, inject form_class to create and update views,
e.g., to customize validation logic for each Concrete Attachment type
In your templates:
Load the attachments_tags:
{% load attachments_tags %}
django-attachments comes with some templatetags to add or delete attachments for your model objects in your frontend.
-
get_attachments_for [object]: Fetches the attachments for the given model instance. You can optionally define a variable name in which the attachment list is stored in the template context. If you do not define a variable name, the result is printed instead.{% get_attachments_for entry as attachments_list %} -
attachments_count [object]: Counts the attachments for the given model instance and returns an int:{% attachments_count entry %} -
attachment_form: Renders a upload form to add attachments for the given model instance. Example:{% attachment_form [object] %}It returns an empty string if the current user is not logged in.
-
attachment_delete_link: Renders a link to the delete view for the given attachment. Example:{% for att in attachments_list %} {{ att }} {% attachment_delete_link att %} {% endfor %}This tag automatically checks for permission. It returns only a html link if the given attachment's creator is the current logged in user or the user has the
delete_foreign_attachmentspermission.
Quick Example:
{% load attachments_tags %}
{% get_attachments_for entry as my_entry_attachments %}
<span>Object has {% attachments_count entry %} attachments</span>
{% if my_entry_attachments %}
<ul>
{% for attachment in my_entry_attachments %}
<li>
<a href="{{ attachment.attachment_file.url }}">{{ attachment.filename }}</a>
{% attachment_delete_link attachment %}
</li>
{% endfor %}
</ul>
{% endif %}
{% attachment_form entry %}
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>
{{ message }}
</li>
{% endfor %}
</ul>
{% endif %}
Overriding Templates
As usual, templates can be overridden by commandeering the namespace of the default template.
To do this, create a /nifty/attachments directory in your app's templates directory,
then override a template by creating a file matching the name of the default template.
Add a folder named for the template_prefix, as defined in urls config, for attachment type-specific templates.
Settings
ATTACHMENTS_FILE_UPLOAD_MAX_SIZEin Mb. Deny file uploads exceeding this value. Default: 10 Mb.ATTACHMENTS_CONTENT_TYPE_WHITELISTiterable of content type strings. Deny file uploads other than these. Default:()- no restrictions by content type.ATTACHMENTS_FILE_UPLOAD_VALIDATORS- an iterable of custom file validator functions executed against each uploaded file. If any of them raisesValidationErrorthe upload will be denied. Default:nifty_attachments.validators.default_validators
Acknowledgments
This project would be impossible to maintain without the help of our generous contributors
Technology Colophon
Without django and the django dev team, the universe would have fewer rainbows and ponies.
This package was originally created with cookiecutter
and the cookiecutter-powder-pypackage project template.
Developing?
Check out the Dev Guide.
Run Tests
Run the testsuite in your local environment using pipenv:
$ cd django-attachments/
$ pipenv install --dev
$ pipenv run pytest attachments/
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file django_nifty_attachments-0.2.0.tar.gz.
File metadata
- Download URL: django_nifty_attachments-0.2.0.tar.gz
- Upload date:
- Size: 28.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
bcce627cd6f1e73a95a8a9f1b9c52cee8130e0c0f9421fd3b779589e2d1abc49
|
|
| MD5 |
a4539b36ab885ac50bd5071a693ee0ad
|
|
| BLAKE2b-256 |
82e7a3b85de007153520edc39a5cb8df600031405d81b09204de49dff3464ad7
|
Provenance
The following attestation bundles were made for django_nifty_attachments-0.2.0.tar.gz:
Publisher:
release.yaml on powderflask/django-nifty-attachments
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
django_nifty_attachments-0.2.0.tar.gz -
Subject digest:
bcce627cd6f1e73a95a8a9f1b9c52cee8130e0c0f9421fd3b779589e2d1abc49 - Sigstore transparency entry: 925610274
- Sigstore integration time:
-
Permalink:
powderflask/django-nifty-attachments@f2f00f800414bcb95a8d3928ad7298cb33ab7a3f -
Branch / Tag:
refs/tags/0.2.0 - Owner: https://github.com/powderflask
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yaml@f2f00f800414bcb95a8d3928ad7298cb33ab7a3f -
Trigger Event:
push
-
Statement type:
File details
Details for the file django_nifty_attachments-0.2.0-py3-none-any.whl.
File metadata
- Download URL: django_nifty_attachments-0.2.0-py3-none-any.whl
- Upload date:
- Size: 22.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
5f4313712e395f40132110a5f36dfb91a4275dab972e5a0e355d90d17b40cbbf
|
|
| MD5 |
3b8b51c17db58042644b560d7b1b741c
|
|
| BLAKE2b-256 |
481d81e0e9090acf9358d160f90eb2569d04c11bb58000d081e5bc07e417ed97
|
Provenance
The following attestation bundles were made for django_nifty_attachments-0.2.0-py3-none-any.whl:
Publisher:
release.yaml on powderflask/django-nifty-attachments
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
django_nifty_attachments-0.2.0-py3-none-any.whl -
Subject digest:
5f4313712e395f40132110a5f36dfb91a4275dab972e5a0e355d90d17b40cbbf - Sigstore transparency entry: 925610283
- Sigstore integration time:
-
Permalink:
powderflask/django-nifty-attachments@f2f00f800414bcb95a8d3928ad7298cb33ab7a3f -
Branch / Tag:
refs/tags/0.2.0 - Owner: https://github.com/powderflask
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yaml@f2f00f800414bcb95a8d3928ad7298cb33ab7a3f -
Trigger Event:
push
-
Statement type: