A file management application for Django that makes handling of files and images a breeze.
—
Django Filer provides custom model fields that integrate filer objects into your Django models with rich admin widgets. These fields automatically handle the relationship to filer objects and provide user-friendly interfaces in the Django admin.
A Django ForeignKey field that creates relationships to filer File objects with an integrated admin widget for file selection.
class FilerFileField(models.ForeignKey):
"""
Django model field for referencing filer File objects.
Automatically configures:
- to='filer.File' (hard-coded target model)
- default_form_class=AdminFileFormField
- Admin widget with file browser popup
Args:
All standard ForeignKey arguments except 'to' (which is fixed)
"""
def __init__(self, **kwargs):
"""Initialize the field, setting target model to filer.File."""
def formfield(self, **kwargs):
"""Return form field with admin widget."""
class AdminFileFormField(forms.ModelChoiceField):
"""Form field class used by FilerFileField in admin."""
def __init__(self, rel, queryset, to_field_name, *args, **kwargs):
"""
Initialize admin form field.
Args:
rel: Field relation object
queryset: QuerySet of available files
to_field_name: Target field name
"""
class AdminFileWidget(ForeignKeyRawIdWidget):
"""Admin widget for file selection with popup browser."""
def render(self, name, value, attrs=None, renderer=None):
"""
Render the widget HTML.
Args:
name (str): Field name
value: Current field value
attrs (dict): HTML attributes
renderer: Template renderer
Returns:
str: Rendered HTML
"""
def label_for_value(self, value):
"""Get display label for the current value."""
def obj_for_value(self, value):
"""Get File object for the given value."""A specialized field for referencing filer Image objects, extending FilerFileField with image-specific functionality.
class FilerImageField(FilerFileField):
"""
Django model field for referencing filer Image objects.
Inherits from FilerFileField but targets Image model by default.
Uses specialized admin widget for image selection.
Args:
All FilerFileField arguments
"""
# Automatically configured
default_form_class = AdminImageFormField
default_model_class = settings.FILER_IMAGE_MODEL
class AdminImageFormField(AdminFileFormField):
"""Form field class used by FilerImageField in admin."""
class AdminImageWidget(AdminFileWidget):
"""Admin widget for image selection with image preview."""A Django ForeignKey field for referencing filer Folder objects with folder browser widget.
class FilerFolderField(models.ForeignKey):
"""
Django model field for referencing filer Folder objects.
Automatically configures:
- to='filer.Folder' (hard-coded target model)
- default_form_class=AdminFolderFormField
- Admin widget with folder browser popup
Args:
All standard ForeignKey arguments except 'to' (which is fixed)
"""
def __init__(self, **kwargs):
"""Initialize the field, setting target model to filer.Folder."""
def formfield(self, **kwargs):
"""Return form field with admin widget."""
class AdminFolderFormField(forms.ModelChoiceField):
"""Form field class used by FilerFolderField in admin."""
def __init__(self, rel, queryset, to_field_name, *args, **kwargs):
"""
Initialize admin form field.
Args:
rel: Field relation object
queryset: QuerySet of available folders
to_field_name: Target field name
"""
class AdminFolderWidget(ForeignKeyRawIdWidget):
"""Admin widget for folder selection with popup browser."""
def render(self, name, value, attrs=None, renderer=None):
"""
Render the widget HTML.
Args:
name (str): Field name
value: Current field value
attrs (dict): HTML attributes
renderer: Template renderer
Returns:
str: Rendered HTML with folder browser
"""
def label_for_value(self, value):
"""Get display label for the current value."""
def obj_for_value(self, value):
"""Get Folder object for the given value."""Internal field used by filer models to support both public and private file storage.
class MultiStorageFileField(models.FileField):
"""
File field supporting both public and private storage backends.
Automatically routes files to appropriate storage based on
the is_public flag of the containing model.
Args:
All standard FileField arguments
"""
def __init__(self, *args, **kwargs):
"""Initialize field with storage configuration."""
class MultiStorageFieldFile:
"""File wrapper class handling public/private storage routing."""
@property
def url(self):
"""Get URL appropriate for the storage type."""
class MultiStorageFileDescriptor:
"""Field descriptor with data change callbacks."""from django.db import models
from filer.fields import FilerFileField, FilerImageField, FilerFolderField
class Article(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
# Optional file attachment
attachment = FilerFileField(
null=True,
blank=True,
related_name="article_attachments",
on_delete=models.SET_NULL
)
# Featured image
featured_image = FilerImageField(
null=True,
blank=True,
related_name="article_images",
on_delete=models.SET_NULL
)
# Category folder
category_folder = FilerFolderField(
null=True,
blank=True,
related_name="article_categories",
on_delete=models.SET_NULL
)
class Gallery(models.Model):
name = models.CharField(max_length=100)
# Multiple images using ManyToManyField
images = models.ManyToManyField(
'filer.Image',
through='GalleryImage',
blank=True
)
class GalleryImage(models.Model):
gallery = models.ForeignKey(Gallery, on_delete=models.CASCADE)
image = FilerImageField(on_delete=models.CASCADE)
order = models.PositiveIntegerField(default=0)
caption = models.CharField(max_length=255, blank=True)from filer.fields import FilerFileField, FilerImageField
class Document(models.Model):
title = models.CharField(max_length=200)
# File field with custom validation
file = FilerFileField(
on_delete=models.CASCADE,
related_name="document_files",
# Add help text for admin
help_text="Upload a PDF or Word document"
)
# Thumbnail image with size constraints
thumbnail = FilerImageField(
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name="document_thumbnails",
help_text="Optional thumbnail image (recommended: 300x200px)"
)
class UserProfile(models.Model):
user = models.OneToOneField('auth.User', on_delete=models.CASCADE)
# Avatar image
avatar = FilerImageField(
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name="user_avatars"
)
# Documents folder
documents_folder = FilerFolderField(
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name="user_document_folders"
)# Accessing file properties through the field
article = Article.objects.get(pk=1)
if article.attachment:
print(f"File name: {article.attachment.name}")
print(f"File URL: {article.attachment.url}")
print(f"File size: {article.attachment.size}")
print(f"File extension: {article.attachment.extension}")
# Check permissions
if article.attachment.has_read_permission(request.user):
# User can access this file
file_url = article.attachment.url
if article.featured_image:
print(f"Image dimensions: {article.featured_image.width}x{article.featured_image.height}")
print(f"Image URL: {article.featured_image.url}")
# Get image EXIF data
exif_data = article.featured_image.exif
if article.category_folder:
print(f"Folder path: {article.category_folder.logical_path}")
print(f"Files in folder: {article.category_folder.file_count}")from django.contrib import admin
from filer.fields import FilerFileField, FilerImageField
class ArticleAdmin(admin.ModelAdmin):
list_display = ['title', 'attachment', 'featured_image']
# Customize the admin interface
fieldsets = (
('Content', {
'fields': ('title', 'content')
}),
('Media', {
'fields': ('featured_image', 'attachment'),
'classes': ('collapse',)
}),
)
# Raw ID fields for better performance with large datasets
raw_id_fields = ['featured_image', 'attachment']
admin.site.register(Article, ArticleAdmin)from django import forms
from filer.fields import FilerFileField
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = ['title', 'content', 'attachment', 'featured_image']
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Customize field widgets for non-admin forms
self.fields['attachment'].widget = forms.HiddenInput()
self.fields['featured_image'].widget = forms.HiddenInput()
# Or use custom widgets
# self.fields['attachment'].widget = CustomFileWidget()All filer fields support standard Django ForeignKey arguments:
# Relationship configuration
on_delete=models.CASCADE # Required
null=True, blank=True # Optional fields
related_name="custom_name" # Reverse relation name
# Admin configuration
help_text="Upload instructions"
verbose_name="Display Name"
# Validation
limit_choices_to={'is_public': True} # Limit available choices# Files are automatically routed to public/private storage
# based on the File.is_public flag
# For guaranteed public access:
class PublicDocument(models.Model):
file = FilerFileField(
on_delete=models.CASCADE,
limit_choices_to={'is_public': True}
)
# For controlled access:
class PrivateDocument(models.Model):
file = FilerFileField(
on_delete=models.CASCADE,
limit_choices_to={'is_public': False}
)Install with Tessl CLI
npx tessl i tessl/pypi-django-filer