Django FileBrowser DocumentationDjango FileBrowser Documentation, Release 3.5.7 Media-Management...

52
Django FileBrowser Documentation Release 3.5.7 Patrick Kranzlmueller July 12, 2015

Transcript of Django FileBrowser DocumentationDjango FileBrowser Documentation, Release 3.5.7 Media-Management...

Django FileBrowser DocumentationRelease 357

Patrick Kranzlmueller

July 12 2015

Contents

1 Installation and Setup 311 Quick start guide 312 Settings 4

2 API 1121 API 11

3 Fields amp Widgets 1931 Fields amp Widgets 19

4 Admin Interface 2341 Admin Interface 23

5 Image Versions 2951 Versions 29

6 Help 3361 Help 3362 Changelog 35

7 Main Features 39

8 Code 41

9 Discussion 43

10 Versions and Compatibility 45

i

ii

Django FileBrowser Documentation Release 357

Media-Management with Grappelli

Note FileBrowser 357 requires Django 141516 or 17 and Grappelli 2425 or 26

Contents 1

Django FileBrowser Documentation Release 357

2 Contents

CHAPTER 1

Installation and Setup

11 Quick start guide

For using the FileBrowser Django needs to be installed and an Admin Site has to be activated

111 Requirements

bull Django 14151617 httpwwwdjangoprojectcom

bull Grappelli 242526 httpsgithubcomsehmaschinedjango-grappelli

bull Pillow httpsgithubcompython-imagingPillow

112 Installation

Install the FileBrowser

pip install django-filebrowser

Add the filebrowser to your INSTALLED_APPS (before djangocontribadmin)

INSTALLED_APPS = (grappellifilebrowserdjangocontribadmin

)

Add the FileBrowser site to your url-patterns (before any admin-urls)

from filebrowsersites import site

urlpatterns = patterns((r^adminfilebrowser include(siteurls))(r^grappelli include(grappelliurls))(r^admin include(adminsiteurls))

)

Collect the static files (please refer to the Staticfiles Documentation for more information)

python managepy collectstatic

3

Django FileBrowser Documentation Release 357

113 Settings

Check the Settings

Note You need to add a folder ldquouploadsrdquo within sitestoragelocation when using the default settingsAnd we strongly recommend to define a VERSIONS_BASEDIR

114 Testing

Run the FileBrowser tests

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Start the devserver and login to your admin site

python managepy runserver ltIP-addressgt8000

Goto adminfilebrowserbrowse and check if everything looksworks as expected If yoursquore having problems seeTroubleshooting

12 Settings

There are some settings in order to customize the FileBrowser Nonetheless you should be able to start with the defaultsettings

All settings can be defined in your projects settings-file In that case you have to use the prefix FILEBROWSER_ forevery setting (eg FILEBROWSER_EXTENSIONS instead of EXTENSIONS)

121 Main URLPaths Settings

MEDIA_ROOT

Warning Will be removed with version 360 Since 34 MEDIA_ROOT is defined with your storage engine

The absolute path to the directory that holds the media-files you want to browse

MEDIA_ROOT = getattr(settings FILEBROWSER_MEDIA_ROOT settingsMEDIA_ROOT)

MEDIA_URL

Warning Will be removed with version 360 Since 34 MEDIA_URL is defined with your storage engine

URL that handles the media served from MEDIA_ROOT

MEDIA_URL = getattr(settings FILEBROWSER_MEDIA_URL settingsMEDIA_URL)

4 Chapter 1 Installation and Setup

Django FileBrowser Documentation Release 357

DIRECTORY (relative to storage location)

Main FileBrowser Directory Leave empty in order to browse all files and folders within a storage location

DIRECTORY = getattr(settings FILEBROWSER_DIRECTORY uploads)

You can override this setting on a perndashsite basis

from filebrowsersites import sitesitedirectory = uploads

122 FileBrowser Media TinyMCE Media

Deprecated since version 353 Use staticfiles instead

123 Extensions and Formats

EXTENSIONS

Allowed extensions for file upload

EXTENSIONS = getattr(settings FILEBROWSER_EXTENSIONS Folder []Image [jpgjpeggifpngtiftiff]Document [pdfdocrtftxtxlscsv]Video [movwmvmpegmpgavirm]Audio [mp3mp4wavaiffmidim4p]

)

SELECT_FORMATS

Set different Options for selecting elements from the FileBrowser

SELECT_FORMATS = getattr(settings FILEBROWSER_SELECT_FORMATS file [FolderImageDocumentVideoAudio]image [Image]document [Document]media [VideoAudio]

)

When using the browse-function for selecting FilesFolders you can use an additional query-attribute type in orderto restrict the choices

124 Versions

VERSIONS_BASEDIR (relative to storage location)

Changed in version 340

Directory to save image versions (and thumbnails) If no directory is given versions are stored at the same location asthe original image

12 Settings 5

Django FileBrowser Documentation Release 357

VERSIONS_BASEDIR = getattr(settings FILEBROWSER_VERSIONS_BASEDIR )

We do recommend the following structure for media files

-- media sitestoragelocation (eg MEDIA_ROOT)-- _versions VERSIONS_BASEDIR (outside of sitedirectory)-- uploads sitedirectory

Warning If VERSIONS_BASEDIR is within sitedirectory it will be browsed

Warning With the next major release (360) the default setting will be ldquo_versionsrdquo

VERSIONS

Define the versions according to your websites grid

VERSIONS = getattr(settings FILEBROWSER_VERSIONS admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

)

VERSION_QUALITY

Quality of saved versions

VERSION_QUALITY = getattr(settings FILEBROWSER_VERSION_QUALITY 90)

ADMIN_VERSIONS

The versions you want to show with the admin interface

ADMIN_VERSIONS = getattr(settings FILEBROWSER_ADMIN_VERSIONS [thumbnail small medium big large])

ADMIN_THUMBNAIL

The version being used as the admin thumbnail

ADMIN_THUMBNAIL = getattr(settings FILEBROWSER_ADMIN_THUMBNAIL admin_thumbnail)

125 Placeholder

With your locale environment you donrsquot necessarily have access to all media files (eg images uploaded by yourclient) Therefore you can use a PLACEHOLDER

6 Chapter 1 Installation and Setup

Django FileBrowser Documentation Release 357

PLACEHOLDER

Path to placeholder image (relative to storage location)

PLACEHOLDER = getattr(settings FILEBROWSER_PLACEHOLDER )

SHOW_PLACEHOLDER

Show placeholder (instead of a version) if the original image does not exist

SHOW_PLACEHOLDER = getattr(settings FILEBROWSER_SHOW_PLACEHOLDER False)

FORCE_PLACEHOLDER

Always show placeholder (even if the original image exists)

FORCE_PLACEHOLDER = getattr(settings FILEBROWSER_FORCE_PLACEHOLDER False)

126 Extra Settings

SAVE_FULL_URL

Deprecated since version 340 With custom storage engines saving the full URL doesnrsquot make sense anymoreMoreover removing this settings allows for easily replacing a FileBrowseField with Djangos File- or ImageField

STRICT_PIL

If set to True the FileBrowser will not try to import a mis-installed PIL

STRICT_PIL = getattr(settings FILEBROWSER_STRICT_PIL False)

IMAGE_MAXBLOCK

see httpmailpythonorgpipermailimage-sig1999-August000816html

IMAGE_MAXBLOCK = getattr(settings FILEBROWSER_IMAGE_MAXBLOCK 10241024)

EXCLUDE

Exclude-patterns for files you donrsquot want to show

EXTENSION_LIST = []for exts in EXTENSIONSvalues()

EXTENSION_LIST += extsEXCLUDE = getattr(settings FILEBROWSER_EXCLUDE (r_((exts)s)__qd13((exts)s) exts (|join(EXTENSION_LIST))))

12 Settings 7

Django FileBrowser Documentation Release 357

MAX_UPLOAD_SIZE

Max Upload Size in Bytes

MAX_UPLOAD_SIZE = getattr(settings FILEBROWSER_MAX_UPLOAD_SIZE 10485760)

NORMALIZE_FILENAME

True if you want to normalize filename on upload and remove all non-alphanumeric characters (except for under-scores spaces amp dashes)

NORMALIZE_FILENAME = getattr(settings FILEBROWSER_NORMALIZE_FILENAME False)

CONVERT_FILENAME

True if you want to convert the filename on upload (replace spaces and convert to lowercase)

CONVERT_FILENAME = getattr(settings FILEBROWSER_CONVERT_FILENAME True)

LIST_PER_PAGE

How many items appear on each paginated list

LIST_PER_PAGE = getattr(settings FILEBROWSER_LIST_PER_PAGE 50)

DEFAULT_SORTING_BY

Default sorting attribute

DEFAULT_SORTING_BY = getattr(settings FILEBROWSER_DEFAULT_SORTING_BY date)

Options are date filesize filename_lower filetype_checked

DEFAULT_SORTING_ORDER

Default sorting order

DEFAULT_SORTING_ORDER = getattr(settings FILEBROWSER_DEFAULT_SORTING_ORDER desc)

Options are asc or desc

FOLDER_REGEX

regex to clean directory names before creation

FOLDER_REGEX = getattr(settings FILEBROWSER_FOLDER_REGEX r^[w_ -]+$)

8 Chapter 1 Installation and Setup

Django FileBrowser Documentation Release 357

SEARCH_TRAVERSE

True if you want to traverse all subdirectories when searching Please note that with thousands of filesdirectoriesthis might take a while

SEARCH_TRAVERSE = getattr(settings FILEBROWSER_SEARCH_TRAVERSE False)

DEFAULT_PERMISSIONS

Default upload and version permissions

DEFAULT_PERMISSIONS = getattr(settings FILEBROWSER_DEFAULT_PERMISSIONS 0755)

OVERWRITE_EXISTING

New in version 351

True in order to overwrite existing files False to use the behaviour of the storage engine

OVERWRITE_EXISTING = getattr(settings FILEBROWSER_OVERWRITE_EXISTING True)

12 Settings 9

Django FileBrowser Documentation Release 357

10 Chapter 1 Installation and Setup

CHAPTER 2

API

21 API

211 FileListing

class FileListing(path filter_func=None sorting_by=None sorting_order=None)Returns a list of FileObjects for a server path see FileObject

Parameters

bull path ndash Relative path to a location within sitestoragelocation

bull filter_func ndash Filter function see example below

bull sorting_by ndash Sort the files by any attribute of FileObject

bull sorting_order ndash Sorting order either ldquoascrdquo or ldquodescrdquo

If you want to list all files within a storage location you do

from filebrowsersites import sitefrom filebrowserbase import FileListingfilelisting = FileListing(sitestoragelocation sorting_by=date sorting_order=desc)

Use a custom filter function to limit the list of files

def filter_filelisting(item) item is a FileObjectreturn itemfiletype = Folder

filelisting = FileListing(sitestoragelocation filter_func=filter_listing sorting_by=date sorting_order=desc)

Methods

For the below examples wersquore using this folder-structure

mediauploadstestfoldertestimagejpgmediauploadsblog1imagesblogimagejpg

Note We defined filter_browse as filter_func (see sitespy) And we did not define aVERSIONS_BASEDIR for this demonstration though it is highly recommended to use one

11

Django FileBrowser Documentation Release 357

listing()Returns all items for the given path with oslistdir(path)

gtgtgt for item in filelistinglisting() print itemblogtestfolder

walk()Returns all items for the given path with oswalk(path)

gtgtgt for item in filelistingwalk() print itemblogblog1blog1imagesblog1imagesblogimagejpgblog1imagesblogimage_admin_thumbnailjpgblog1imagesblogimage_mediumjpgblog1imagesblogimage_smalljpgblog1imagesblogimage_thumbnailjpgtestfoldertestfoldertestimagejpg

files_listing_total()Returns a sorted list of FileObjects for listing()

gtgtgt for item in filelistingfiles_listing_total() print itemuploadsbloguploadstestfolder

files_walk_total()Returns a sorted list of FileObjects for walk()

gtgtgt for item in filelistingfiles_walk_total() print itemuploadsbloguploadsblog1uploadsblog1imagesuploadsblog1imagesblogimagejpguploadsblog1imagesblogimage_admin_thumbnailjpguploadsblog1imagesblogimage_mediumjpguploadsblog1imagesblogimage_smalljpguploadsblog1imagesblogimage_thumbnailjpguploadstestfolderuploadstestfoldertestimagejpg

files_listing_filtered()Returns a sorted and filtered list of FileObjects for listing()

gtgtgt for item in filelistingfiles_listing_filtered() print itemuploadsbloguploadstestfolder

files_walk_filtered()Returns a sorted and filtered list of FileObjects for walk()

12 Chapter 2 API

Django FileBrowser Documentation Release 357

gtgtgt for item in filelistingfiles_walk_filtered() print itemuploadsbloguploadsblog1uploadsblog1imagesuploadsblog1imagesblogimagejpguploadstestfolderuploadstestfoldertestimagejpg

Note The versions are not listed (compared with files_walk_total) because of filter_func

results_listing_total()Number of total files based on files_listing_total()

gtgtgt filelistingresults_listing_total()2

results_walk_total()Number of total files based on files_walk_total()

gtgtgt filelistingresults_walk_total()10

results_listing_filtered()Number of filtered files based on files_listing_filtered()

gtgtgt filelistingresults_listing_filtered()2

results_walk_filtered()Number of filtered files based on files_walk_filtered()

gtgtgt filelistingresults_walk_filtered()6

212 FileObject

class FileObject(path site=None)An object representing a media file

Parameters

bull path ndash Relative path to a location within sitestoragelocation

bull site ndash An optional FileBrowser Site

For example

from filebrowsersites import sitefrom filebrowserbase import FileObjectfileobject = FileObject(ospathjoin(sitedirectorytestfoldertestimagejpg))version = FileObject(ospathjoin(fileobjectversions_basedir testfolder testimage_mediumjpg))

21 API 13

Django FileBrowser Documentation Release 357

Attributes

Initial Attributes

pathPath relative to a storage location (including sitedirectory)

gtgtgt fileobjectpathuploadstestfoldertestimagejpg

headThe directory name of pathname path

gtgtgt fileobjectheaduploadstestfolder

filenameName of the file (including the extension) or name of the folder

gtgtgt fileobjectfilenametestimagejpg

filename_lowerLower type of filename

filename_rootFilename without extension

gtgtgt fileobjectfilename_roottestimage

extensionFile extension including the dot With a folder the extensions is None

gtgtgt fileobjectextensionjpg

mimetypeMimetype based on httpdocspythonorglibrarymimetypeshtml

gtgtgt fileobjectmimetype(imagejpeg None)

General Attributes

filetypeType of the file as defined with EXTENSIONS

gtgtgt fileobjectfiletypeImage

filesizeFilesize in Bytes

gtgtgt fileobjectfilesize870037L

14 Chapter 2 API

Django FileBrowser Documentation Release 357

dateDate based on timemktime

gtgtgt fileobjectdate12997603470

datetimeDatetime object

gtgtgt fileobjectdatetimedatetimedatetime(2011 3 10 13 32 27)

existsTrue if the path exists False otherwise

gtgtgt fileobjectexistsTrue

Path and URL attributes

pathPath relative to a storage location (including sitedirectory)

gtgtgt fileobjectpathuploadstestfoldertestimagejpg

path_relative_directoryPath relative to sitedirectory

gtgtgt fileobjectpath_relative_directorytestfoldertestimagejpg

path_fullAbsolute server path (based on storagepath)

gtgtgt fileobjectpath_fullabsolutepathtoserverlocationtestfoldertestimagejpg

dirnameNew in version 34

The directory (not including sitedirectory)

gtgtgt fileobjectdirnametestfolder

urlURL for the filefolder (based on storageurl)

gtgtgt fileobjecturlmediauploadstestfoldertestimagejpg

Image attributes

The image attributes are only useful if the FileObject represents an image

dimensionsImage dimensions as a tuple

21 API 15

Django FileBrowser Documentation Release 357

gtgtgt fileobjectdimensions(1000 750)

widthImage width in px

gtgtgt fileobjectwidth1000

heightImage height in px

gtgtgt fileobjectheight750

aspectratioAspect ratio (float format)

gtgtgt fileobjectaspectratio133534908

orientationImage orientation either Landscape or Portrait

gtgtgt fileobjectorientationLandscape

Folder attributes

The folder attributes make sense when the FileObject represents a directory (not a file)

directory

Deprecated since version 353 Use path_relative_directory instead

folder

Deprecated since version 353 Use dirname instead

is_folderTrue if path is a folder

gtgtgt fileobjectis_folderFalse

is_emptyTrue if the folder is empty False if the folder is not empty or the FileObject is not a folder

gtgtgt fileobjectis_emptyFalse

Version attributes

is_versiontrue if the File is a version of another File

16 Chapter 2 API

Django FileBrowser Documentation Release 357

gtgtgt fileobjectis_versionFalsegtgtgt versionis_versionTrue

versions_basedirThe relative path (from storage location) to the main versions folder Either VERSIONS_BASEDIR orsitedirectory

gtgtgt fileobjectversions_basedir_versionsgtgtgt versionversions_basedir_versions

originalReturns the original FileObject

gtgtgt fileobjectoriginalltFileObject uploadstestfoldertestimagejpggtgtgtgt versionoriginalltFileObject uploadstestfoldertestimagejpggt

original_filenameGet the filename of an original image from a version

gtgtgt fileobjectoriginal_filenametestimagejpggtgtgt versionoriginal_filenametestimagejpg

Methods

Version methods

versions()List all filenames based on VERSIONS

gtgtgt fileobjectversions()[_versionstestfoldertestimage_admin_thumbnailjpg_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionversions()[]

Note The versions are not being generated

admin_versions()List all filenames based on ADMIN_VERSIONS

gtgtgt fileobjectadmin_versions()[_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg

21 API 17

Django FileBrowser Documentation Release 357

_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionadmin_versions()[]

Note The versions are not being generated

version_name(version_suffix)Get the filename for a version

gtgtgt fileobjectversion_name(medium)testimage_mediumjpg

Note The version is not being generated

version_path(version_suffix)Get the path for a version

gtgtgt fileobjectversion_path(medium)_versionstestfoldertestimage_mediumjpg

Note The version is not being generated

version_generate(version_suffix)Generate a version

gtgtgt fileobjectversion_generate(medium)ltFileObject uploadstestfoldertestimage_mediumjpggt

Please note that a version is only generated if it does not already exist or if the original image is newer than theexisting version

Delete methods

delete()Delete the File or Folder from the server

Warning If you delete a Folder all items within the folder are being deleted

delete_versions()Delete all VERSIONS

delete_admin_versions()Delete all ADMIN_VERSIONS

18 Chapter 2 API

CHAPTER 3

Fields amp Widgets

31 Fields amp Widgets

The FileBrowseField is a custom model field which returns a FileObject The widgets FileInput and ClearableFileIn-put are used with the admin app in order to show an additional thumbnail for images

311 FileBrowseField

class FileBrowseField(max_length[ site directory extensions format options])A subclass of CharField referencing a media file within Returns a FileObject

Parameters

bull site ndash A FileBrowser site (defaults to the main site) see FileBrowser Site

bull directory ndash Directory to browse when clicking the search icon

bull extensions ndash List of allowed extensions see Extensions and Formats

bull format ndash A key from SELECT_FORMATS in order to restrict the selection to specificfiletypes see Extensions and Formats

For example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 directory=images extensions=[jpg] blank=True null=True)document = FileBrowseField(PDF max_length=200 directory=documents extensions=[pdfdoc] blank=True null=True)

FileBrowseField in Templates

You can use all attributes from FileObject

blogentryimage ltimg src= publicationimageurl gt

ifequal blogentryimageimage_orientation landscape ltimg src= blogentryimageurl class=landscape gt

endifequal

19

Django FileBrowser Documentation Release 357

Showing Thumbnail in the Changelist

To show a thumbnail with the changelist you can define a ModelAdmin method

from filebrowsersettings import ADMIN_THUMBNAIL

def image_thumbnail(self obj)if objimage and objimagefiletype == Image

return ltimg src=s gt objimageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Using the FileBrowseField with TinyMCE

In order to replace the TinyMCE imagefile manager with the FileBrowser you have to use a FileBrowser CallbackTherersquos an example TinyMCE configuration file in staticjs called TinyMCEAdminjs You can either copy theFileBrowserCallback to your own file or just use tinymce_setupjs (which comes with django-grappelli)

Just add these lines to your ModelAdmin asset definitions

class Mediajs = [pathtotinymcejscriptstiny_mcetiny_mcejs

pathtoyourtinymce_setupjs]

312 FileInput

Subclass of FileInput with an additional thumbnail

from filebrowserwidgets import FileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget FileInput

313 ClearableFileInput

Subclass of ClearableFileInput with an additional thumbnail

from filebrowserwidgets import ClearableFileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget ClearableFileInput

314 Django FileField and the FileBrowser

Return a FileObject from a FileField or ImageField with

20 Chapter 3 Fields amp Widgets

Django FileBrowser Documentation Release 357

from filebrowserbase import FileObject

image_upload = modelsImageField(uImage (Upload) max_length=250 upload_to=image_upload_path blank=True null=True)

def image(self)if selfimage_upload

return FileObject(selfimage_uploadpath)return None

In order show a thumbnail with your changelist you could use a ModelAdmin method

from filebrowserbase import FileObject

def image_thumbnail(self obj)if objimage_upload

image = FileObject(objimage_uploadpath)if imagefiletype == Image

return ltimg src=s gt imageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Note There are different ways to achieve this The above examples show one of several options

31 Fields amp Widgets 21

Django FileBrowser Documentation Release 357

22 Chapter 3 Fields amp Widgets

CHAPTER 4

Admin Interface

41 Admin Interface

The main FileBrowser admin application is an extension for the Django admin interface in order to browser yourmedia folder upload and renamedelete files

411 FileBrowser Site

New in version 340

class FileBrowserSite(name=None app_name=rsquofilebrowserrsquo storage=default_storage)Respresents the FileBrowser admin application (similar to Djangorsquos admin site)

Parameters

bull name ndash A name for the site defaults to None

bull app_name ndash Defaults to lsquofilebrowserrsquo

bull storage ndash A custom storage engine defaults to Djangos default storage

Similar to djangocontribadmin you first need to add a filebrowsersite to your admin interface Inyour urlspy import the default FileBrowser site (or your custom site) and add the site to your URL-patterns (beforeany admin-urls)

from filebrowsersites import site

urlpatterns = patterns(url(r^adminurlfilebrowser include(siteurls))

)

Now you are able to browse the location defined with the storage engine associated to your site

from djangocorefilesstorage import DefaultStoragefrom filebrowsersites import FileBrowserSite

Default FileBrowser sitesite = FileBrowserSite(name=filebrowser storage=DefaultStorage())

My Custom FileBrowser sitecustom_site = FileBrowserSite(name=custom_filebrowser storage=DefaultStorage())custom_sitedirectory = custom_uploads

23

Django FileBrowser Documentation Release 357

Note The module variable site from filebrowsersites is the default FileBrowser application

412 Custom Actions

New in version 340

Similar to Djangorsquos admin actions you can define your FileBrowser actions and thus automate the typical tasks ofyour users Registered custom actions are listed in the detail view of a file and a user can select a single action at atime The selected action will then be applied to the file

The default FileBrowser image actions such as ldquoFlip Verticalrdquo or ldquoRotate 90deg Clockwiserdquo are in fact implemented ascustom actions (see the module filebrowseractions)

Writing Your Own Actions

Custom actions are simple functions

def foo(request fileobjects) Do something with the fileobjects

The first parameter is a HttpRequest object (representing the submitted form in which a user selected the action)and the second parameter is a list of FileObjects to which the action should be applied

The list contains exactly one instance of FileObject (representing the file from the detail view) but this may change inthe future as custom actions may become available also in browse views (similar to admin actions applied to a list ofchecked objects)

Registering an Action

In order to make your action visible you need to register it with a FileBrowser site

siteadd_action(foo)

Once registered the action will appear in the detail view of a file You can also give your action a short description

fooshort_description = Do foo with the File

This short description will then appear in the list of available actions If you do not provide a short description thefunction name will be used instead and FileBrowser will replace any underscores in the function name with spaces

Associating Actions with Specific Files

Each custom action can be associated with a specific file type (eg images audio file etc) to which it applies In orderto do that you need to define a predicatefilter function which takes a single argument (FileObject) and returns Trueif your action is applicable to that FileObject Finally you need to register this filter function with your action

fooapplies_to(lambda fileobject fileobjectfiletype == Image)

In the above example foo will appear in the action list only for image files If you do not specify any filter functionfor your action FileBrowser considers the action as applicable to all files

24 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

Messages amp Intermediate Pages

You can provide a feedback to a user about a successful or failed execution of an action by using a message Forexample

from djangocontrib import messages

def desaturate_image(request fileobjects)for f in fileobjects

Desaturate the imagemessagesadd_message(request messagesSUCCESS _(Image s was desaturated) ffilename)

Some actions may require user confirmation (eg in order to prevent accidental and irreversible modification tofiles) In order to that follow the same pattern as with Djangorsquos admin action and return a HttpResponse objectfrom your action Good practice for intermediate pages is to implement a confirm view and have your action returnHttpResponseRedirect

def crop_image(request fileobjects)files = ampf=join([fpath_relative for f in fileobjects])return HttpResponseRedirect(confirmaction=crop_imageampf=s files)

413 File Storages

New in version 340

You have the option to specify which file storage engine a FileBrowser should use to browseuploadmodify yourmedia files This enables you to use a FileBrowser even if your media files are located at some remote system Seealso the Djangorsquos documentation on storages httpsdocsdjangoprojectcomendevtopicsfiles

To associate a FileBrowser site with a particular storage engine set the storage property of a site object

from djangocorefilesstorage import FileSystemStoragesitestorage = FileSystemStorage(location=pathtomediadirectory base_url=media)

For storage classes other than FileSystemStorage (or those that inherit from that class) therersquos more effort involved inproviding a storage object that can be used with FileBrowser See StorageMixin Class

Note Prior FileBrowser 34 the way to specify FileBrowserlsquos MEDIA_ROOT and MEDIA_URL was via settingspyStarting from version 34 those variables are associated with the storage instance and you can set them as illustratedin the above example

Warning For the reason of backward compatibility FileBrowser settings FILEBROWSER_MEDIA_ROOT andFILEBROWSER_MEDIA_URL can still be used to customize FileBrowser as long as yoursquore using the defaultFileBrowserlsquos site without having changed its storage engine In the next major release of FileBrowser thesesettings will be removed

StorageMixin Class

A FileBrowser uses the Djangorsquos Storage class to access media files However the API of the Storageclass does not provide all methods necessary for FileBrowserrsquos functionality A StorageMixin class fromfilebrowserstorage module therefore defines all the additional methods that a FileBrowser requires

isdir(self name)Returns true if name exists and is a directory

41 Admin Interface 25

Django FileBrowser Documentation Release 357

isfile(self name)Returns true if name exists and is a regular file

move(self old_file_name new_file_name allow_overwrite=False)Moves safely a file from one location to another If allow_ovewrite==False and new_file_nameexists raises an exception

makedirs(self name)Creates all missing directories specified by name Analogue to osmkdirs()

414 Views

All views use the staff_member_requird and path_exists decorator in order to check if the server pathactually exists Some views also use the file_exists decorator

bull Browse fb_browse Browse a directory on your server Returns a FileListing

ndash Optional query string args dir o ot q p filter_date filter_type type

bull Create directory fb_createdir Create a new folder on your server

ndash Optional query string args dir

ndash Signals filebrowser_pre_createdir filebrowser_post_createdir

bull Upload fb_upload Multiple upload

ndash Optional query string args dir type

ndash Signals filebrowser_pre_upload filebrowser_post_upload

bull Edit fb_edit Edit a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_rename filebrowser_post_rename

You are able to apply custom actions (see Custom Actions) to the edit-view

bull Confirm delete fb_confirm_delete Confirm the deletion of a file or folder

ndash Required query string args filename

ndash Optional query string args dir

If you try to delete a folder all filesfolders within this folder are listed on this page

bull Delete fb_delete Delete a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_delete filebrowser_post_delete

Warning If you delete a Folder all items within this Folder are being deleted

bull Version fb_version Generate a version of an image as defined with ADMIN_VERSIONS

ndash Required query string args filename

ndash Optional Query string args dir

This is a helper used by the FileBrowseField and TinyMCE for selecting a version

26 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

415 Signals

The FileBrowser sends a couple of different signals Please take a look at the module filebrowsersignals for furtherexplanation on the provided arguments

bull filebrowser_pre_upload Sent before a an Upload starts

bull filebrowser_post_upload Sent after an Upload has finished

bull filebrowser_pre_delete Sent before an Item (File Folder) is deleted

bull filebrowser_post_delete Sent after an Item (File Folder) has been deleted

bull filebrowser_pre_createdir Sent before a new Folder is created

bull filebrowser_post_createdir Sent after a new Folder has been created

bull filebrowser_pre_rename Sent before an Item (File Folder) is renamed

bull filebrowser_post_rename Sent after an Item (File Folder) has been renamed

bull filebrowser_actions_pre_apply Sent before a custom action is applied

bull filebrowser_actions_post_apply Sent after a custom action has been applied

Example for using these Signals

Herersquos a small example for using the above Signals

from filebrowser import signals

def pre_upload_callback(sender kwargs)Receiver function called before an upload startsprint Pre Upload Callbackprint kwargs kwargs

signalsfilebrowser_pre_uploadconnect(pre_upload_callback)

def post_upload_callback(sender kwargs)Receiver function called each time an upload has finishedprint Post Upload Callbackprint kwargs kwargs You can use all attributes available with the FileObject This is just an example print Filesize kwargs[file]filesizeprint Orientation kwargs[file]orientationprint Extension kwargs[file]extension

signalsfilebrowser_post_uploadconnect(post_upload_callback)

41 Admin Interface 27

Django FileBrowser Documentation Release 357

28 Chapter 4 Admin Interface

CHAPTER 5

Image Versions

51 Versions

With the FileBrowser you are able to define different versionssizes for images This enables you to save an originalimage on your server while having different versions of that image to automatically fit your websites grid Versionsare also useful for responsiveadaptive layouts

511 Defining Versions

New in version 340 methods

First you need to know which versionssizes of an image yoursquod like to generate with your website Letrsquos say yoursquoreusing a 12 column grid with 60px for each column and 20px margin (which is a total of 940px) With this grid youcould (for example) define these image versions

FILEBROWSER_VERSIONS_BASEDIR = _versionsFILEBROWSER_VERSIONS =

admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

Use the methods argument if you need to add a filter

def grayscale(im)Convert image to grayscaleif immode = L

im = imconvert(L)return im

FILEBROWSER_VERSIONS = big verbose_name Big (6 col) width 460 height opts methods [grayscale]

)

29

Django FileBrowser Documentation Release 357

512 Versions and the Admin

When using the FileBrowser with the admin interface you need to define ADMIN_VERSIONS andADMIN_THUMBNAIL (see Settings) ADMIN_VERSIONS are available with the admin ie you are able to seethese versions with the image detail view and you are able to select the versions with the FileBrowseField model field

FILEBROWSER_ADMIN_VERSIONS = [thumbnail small medium big large]FILEBROWSER_ADMIN_THUMBNAIL = admin_thumbnail

513 Versions and the Frontend

With your templates you have two different tags to choose from version and version_object With bothtags the version will be generated if it doesnrsquot already exist OR if the original image is newer than the version Inorder to update an image you just overwrite the original image and the versions will be generated automatically (asyou request them within your template)

A Model example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 blank=True null=True)

With your templates use version if you simply need to retrieve the URL or version_object if you need to geta FileObject

lt-- load filebrowser templatetags --gt load fb_versions

lt-- get the url with version --gtltimg src= version blogentryimage medium gt

lt-- get a fileobject with version_object --gt version_object blogentryimage medium as version_medium version_mediumwidth ltimg src= version_medium gt

Templatetag version

RetrievesGenerates a version and returns an URL

version modelfield_name version_prefix

Templatetag version_object

RetrievesGenerates a version and returns a FileObject

version_object modelfield_name version_prefix as variable

Note With both templatetags version_prefix can either be a string or a variable If version_prefix is astring use quotes

30 Chapter 5 Image Versions

Django FileBrowser Documentation Release 357

514 Versions in Views

If you have a FileObject you can generateretrieve a version with

v = objimageversion_generate(version_prefix) returns a FileObject

515 Placeholder

When developing on a locale machine or a development-server you might not have all the images (resp media-files)available that are on your production instance and downloading these files on a regular basis might not be an option

In that case you can use a placeholder instead of a version You just need to define the PLACEHOLDER and overwritethe settings SHOW_PLACEHOLDER andor FORCE_PLACEHOLDER (see Placeholder)

516 Management Commands

fb_version_generateIf you need to generate certain (or all) versions type

python managepy fb_version_generate

fb_version_removeIf you need to generate certain (or all) versions type

python managepy fb_version_generate

Warning Please be very careful with this command

51 Versions 31

Django FileBrowser Documentation Release 357

32 Chapter 5 Image Versions

CHAPTER 6

Help

61 Help

611 FAQ

Why should I use the FileBrowser

If you need your editors or customers to manage files the FileBrowser is an alternative to an FTP-client Moreoveryou are able to define different image versions according to your websites grid Alternatives to the FileBrowser can befound at httpdjangopackagescomgridsgfile-managers

Do I need Grappelli

Grappelli is a requirement for using the FileBrowser There are several filebrowser-no-grappelli repositories (most ofthem on GitHub) but we donrsquot follow the development

I need help

see Troubleshooting

Why are there no fancy effects

The FileBrowser is about managing files We think that you should prepare your files before uploading them to theserver

How do I upload to another server

Use a custom storage engine see httpsdocsdjangoprojectcomen16howtocustom-file-storage

Why do I need image-versions

You need image-versions if your website is based on a grid

33

Django FileBrowser Documentation Release 357

Is the FileBrowser stable

Wersquove developed the FileBrowser for a couple of years and use it with almost all of our clients That said Grappelli isthe more stable and mature application

How can I contribute

Help is very much needed and appreciated Test the FileBrowser and submit feedbackpatches

Who develops the FileBrowser

The FileBrowser is developed and maintained by Patrick Kranzlmuumlller amp Axel Swoboda of vonautomatisch

612 Troubleshooting

Check your setup

Please check if the problem is caused by your setup

bull Read Quick start guide

bull Check if the staticmedia-files are served correctly

bull Make sure you have removed all custom FileBrowser templates from all locations in TEMPLATE_DIRS orcheck that these templates are compatible with the FileBrowser

Run the tests

Start the shell and type

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Check issues

If your setup is fine please check if your problem is a known issue

bull Take a look at all FileBrowser Issues (incuding closed) and search the FileBrowser Google-Group

Add a ticket

If you think yoursquove found a bug please add a ticket

bull Try to describe your problem as precisely as possible

bull Tell us what you did in order to solve the problem

bull Tell us what version of the FileBrowser you are using

bull Tell us what version of Django you are using

34 Chapter 6 Help

Django FileBrowser Documentation Release 357

bull Please do NOT add tickets if yoursquore having problems with serving staticmedia-files (because this is not relatedto the FileBrowser)

bull Please do NOT add tickets referring to Djangos trunk version

bull At best add a patch

Note Be aware that we may close issues not following these guidlines without further notifications

613 Translation

Translation is done via Transifex

Supported Languages

see httpswwwtransifexnetprojectspdjango-filebrowserresourcedjangopo

614 FileBrowser 35 Release Notes

FileBrowser 35 is compatible with Django 14151617 as well as Grappelli 242526

Update from FileBrowser 34x

bull Update Django to 14151617 and check httpsdocsdjangoprojectcomendevreleases14 orhttpsdocsdjangoprojectcomendevreleases15 or httpsdocsdjangoprojectcomendevreleases16

bull Update Grappelli to 24x25x26x

bull Update FileBrowser to 35x

62 Changelog

621 358 (not yet released)

622 357 (September 10th 2014)

bull New Compatibility with Django 17 and Grappelli 26x

bull Improved Updated tests because of the new random suffix with get_available_name (django storage)

bull Improved Added an icon in order to mark finished uploads

bull Improved Show resulting filename (eg with suffix converted) after successful upload

bull Fixed Permissions with file upload

bull Fixed Unified json response with _upload_file (no matter if file already exists or not)

623 356 (April 16th 2014)

bull Fixed Displaying pagination correctly with lots of entries

62 Changelog 35

Django FileBrowser Documentation Release 357

624 355 (April 13th 2014)

bull New Added client-side (JavaScript) file extension validation to the AJAX uploader

bull New Added experimental Python 33 support

bull Improved Tests with convertnormalize (removed special chars from test filename)

bull Fixed File selection after using search box (CKEditor)

bull Fixed Removed encoding of file URIs with CKEditor

625 354 (February 21st 2014)

bull Fixed Placeholder functionality (including tests)

bull Fixed Convertnormalize filenames (including tests)

bull Fixed Handling uppercase extensions with browse

626 353 (January 7 2014)

bull New added path_full to FileObject

bull Improved added docx to EXTENSIONS

bull Improved Recommend pillow instead of PIL as a requirement

bull Improved Added additional test cases

bull Improved Updated documentation

bull Improved Consistent use of storage (eg storagelocation storageurl)

bull Improved Removed unnecessary functions (eg url_join url_strip)

bull Improved Moved sort_by_attr to FileListing

bull Improved Regex matches with file versions on browse

bull Improved Using djangoconfurls (with djangoconfurlsdefaults as fallback)

bull Improved Adding CONTRIBUTINGrst

bull Improved Removed static Media inner class with fields

bull Improved Removed search icon with fields (has not being used)

bull Improved Added custom class attributes with filebrowser field

bull Improved Updated translations

bull Fixed fixed exception handling with python 25

bull Fixed fixes dir with SEARCH_TRAVERSE true and version select

bull Fixed Make Django FileUploadHandlers work (also fixed a memory leak)

bull Fixed return correct filename with OVERWRITE_EXISTING

bull Fixed fb_version_generate with FILEBROWSER_VERSIONS_BASEDIR

bull Fixed Table sorting with ascdesc

bull Fixed Added DeprecationWarning for FileObjectdirectory and FileObjectfolder

36 Chapter 6 Help

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

Contents

1 Installation and Setup 311 Quick start guide 312 Settings 4

2 API 1121 API 11

3 Fields amp Widgets 1931 Fields amp Widgets 19

4 Admin Interface 2341 Admin Interface 23

5 Image Versions 2951 Versions 29

6 Help 3361 Help 3362 Changelog 35

7 Main Features 39

8 Code 41

9 Discussion 43

10 Versions and Compatibility 45

i

ii

Django FileBrowser Documentation Release 357

Media-Management with Grappelli

Note FileBrowser 357 requires Django 141516 or 17 and Grappelli 2425 or 26

Contents 1

Django FileBrowser Documentation Release 357

2 Contents

CHAPTER 1

Installation and Setup

11 Quick start guide

For using the FileBrowser Django needs to be installed and an Admin Site has to be activated

111 Requirements

bull Django 14151617 httpwwwdjangoprojectcom

bull Grappelli 242526 httpsgithubcomsehmaschinedjango-grappelli

bull Pillow httpsgithubcompython-imagingPillow

112 Installation

Install the FileBrowser

pip install django-filebrowser

Add the filebrowser to your INSTALLED_APPS (before djangocontribadmin)

INSTALLED_APPS = (grappellifilebrowserdjangocontribadmin

)

Add the FileBrowser site to your url-patterns (before any admin-urls)

from filebrowsersites import site

urlpatterns = patterns((r^adminfilebrowser include(siteurls))(r^grappelli include(grappelliurls))(r^admin include(adminsiteurls))

)

Collect the static files (please refer to the Staticfiles Documentation for more information)

python managepy collectstatic

3

Django FileBrowser Documentation Release 357

113 Settings

Check the Settings

Note You need to add a folder ldquouploadsrdquo within sitestoragelocation when using the default settingsAnd we strongly recommend to define a VERSIONS_BASEDIR

114 Testing

Run the FileBrowser tests

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Start the devserver and login to your admin site

python managepy runserver ltIP-addressgt8000

Goto adminfilebrowserbrowse and check if everything looksworks as expected If yoursquore having problems seeTroubleshooting

12 Settings

There are some settings in order to customize the FileBrowser Nonetheless you should be able to start with the defaultsettings

All settings can be defined in your projects settings-file In that case you have to use the prefix FILEBROWSER_ forevery setting (eg FILEBROWSER_EXTENSIONS instead of EXTENSIONS)

121 Main URLPaths Settings

MEDIA_ROOT

Warning Will be removed with version 360 Since 34 MEDIA_ROOT is defined with your storage engine

The absolute path to the directory that holds the media-files you want to browse

MEDIA_ROOT = getattr(settings FILEBROWSER_MEDIA_ROOT settingsMEDIA_ROOT)

MEDIA_URL

Warning Will be removed with version 360 Since 34 MEDIA_URL is defined with your storage engine

URL that handles the media served from MEDIA_ROOT

MEDIA_URL = getattr(settings FILEBROWSER_MEDIA_URL settingsMEDIA_URL)

4 Chapter 1 Installation and Setup

Django FileBrowser Documentation Release 357

DIRECTORY (relative to storage location)

Main FileBrowser Directory Leave empty in order to browse all files and folders within a storage location

DIRECTORY = getattr(settings FILEBROWSER_DIRECTORY uploads)

You can override this setting on a perndashsite basis

from filebrowsersites import sitesitedirectory = uploads

122 FileBrowser Media TinyMCE Media

Deprecated since version 353 Use staticfiles instead

123 Extensions and Formats

EXTENSIONS

Allowed extensions for file upload

EXTENSIONS = getattr(settings FILEBROWSER_EXTENSIONS Folder []Image [jpgjpeggifpngtiftiff]Document [pdfdocrtftxtxlscsv]Video [movwmvmpegmpgavirm]Audio [mp3mp4wavaiffmidim4p]

)

SELECT_FORMATS

Set different Options for selecting elements from the FileBrowser

SELECT_FORMATS = getattr(settings FILEBROWSER_SELECT_FORMATS file [FolderImageDocumentVideoAudio]image [Image]document [Document]media [VideoAudio]

)

When using the browse-function for selecting FilesFolders you can use an additional query-attribute type in orderto restrict the choices

124 Versions

VERSIONS_BASEDIR (relative to storage location)

Changed in version 340

Directory to save image versions (and thumbnails) If no directory is given versions are stored at the same location asthe original image

12 Settings 5

Django FileBrowser Documentation Release 357

VERSIONS_BASEDIR = getattr(settings FILEBROWSER_VERSIONS_BASEDIR )

We do recommend the following structure for media files

-- media sitestoragelocation (eg MEDIA_ROOT)-- _versions VERSIONS_BASEDIR (outside of sitedirectory)-- uploads sitedirectory

Warning If VERSIONS_BASEDIR is within sitedirectory it will be browsed

Warning With the next major release (360) the default setting will be ldquo_versionsrdquo

VERSIONS

Define the versions according to your websites grid

VERSIONS = getattr(settings FILEBROWSER_VERSIONS admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

)

VERSION_QUALITY

Quality of saved versions

VERSION_QUALITY = getattr(settings FILEBROWSER_VERSION_QUALITY 90)

ADMIN_VERSIONS

The versions you want to show with the admin interface

ADMIN_VERSIONS = getattr(settings FILEBROWSER_ADMIN_VERSIONS [thumbnail small medium big large])

ADMIN_THUMBNAIL

The version being used as the admin thumbnail

ADMIN_THUMBNAIL = getattr(settings FILEBROWSER_ADMIN_THUMBNAIL admin_thumbnail)

125 Placeholder

With your locale environment you donrsquot necessarily have access to all media files (eg images uploaded by yourclient) Therefore you can use a PLACEHOLDER

6 Chapter 1 Installation and Setup

Django FileBrowser Documentation Release 357

PLACEHOLDER

Path to placeholder image (relative to storage location)

PLACEHOLDER = getattr(settings FILEBROWSER_PLACEHOLDER )

SHOW_PLACEHOLDER

Show placeholder (instead of a version) if the original image does not exist

SHOW_PLACEHOLDER = getattr(settings FILEBROWSER_SHOW_PLACEHOLDER False)

FORCE_PLACEHOLDER

Always show placeholder (even if the original image exists)

FORCE_PLACEHOLDER = getattr(settings FILEBROWSER_FORCE_PLACEHOLDER False)

126 Extra Settings

SAVE_FULL_URL

Deprecated since version 340 With custom storage engines saving the full URL doesnrsquot make sense anymoreMoreover removing this settings allows for easily replacing a FileBrowseField with Djangos File- or ImageField

STRICT_PIL

If set to True the FileBrowser will not try to import a mis-installed PIL

STRICT_PIL = getattr(settings FILEBROWSER_STRICT_PIL False)

IMAGE_MAXBLOCK

see httpmailpythonorgpipermailimage-sig1999-August000816html

IMAGE_MAXBLOCK = getattr(settings FILEBROWSER_IMAGE_MAXBLOCK 10241024)

EXCLUDE

Exclude-patterns for files you donrsquot want to show

EXTENSION_LIST = []for exts in EXTENSIONSvalues()

EXTENSION_LIST += extsEXCLUDE = getattr(settings FILEBROWSER_EXCLUDE (r_((exts)s)__qd13((exts)s) exts (|join(EXTENSION_LIST))))

12 Settings 7

Django FileBrowser Documentation Release 357

MAX_UPLOAD_SIZE

Max Upload Size in Bytes

MAX_UPLOAD_SIZE = getattr(settings FILEBROWSER_MAX_UPLOAD_SIZE 10485760)

NORMALIZE_FILENAME

True if you want to normalize filename on upload and remove all non-alphanumeric characters (except for under-scores spaces amp dashes)

NORMALIZE_FILENAME = getattr(settings FILEBROWSER_NORMALIZE_FILENAME False)

CONVERT_FILENAME

True if you want to convert the filename on upload (replace spaces and convert to lowercase)

CONVERT_FILENAME = getattr(settings FILEBROWSER_CONVERT_FILENAME True)

LIST_PER_PAGE

How many items appear on each paginated list

LIST_PER_PAGE = getattr(settings FILEBROWSER_LIST_PER_PAGE 50)

DEFAULT_SORTING_BY

Default sorting attribute

DEFAULT_SORTING_BY = getattr(settings FILEBROWSER_DEFAULT_SORTING_BY date)

Options are date filesize filename_lower filetype_checked

DEFAULT_SORTING_ORDER

Default sorting order

DEFAULT_SORTING_ORDER = getattr(settings FILEBROWSER_DEFAULT_SORTING_ORDER desc)

Options are asc or desc

FOLDER_REGEX

regex to clean directory names before creation

FOLDER_REGEX = getattr(settings FILEBROWSER_FOLDER_REGEX r^[w_ -]+$)

8 Chapter 1 Installation and Setup

Django FileBrowser Documentation Release 357

SEARCH_TRAVERSE

True if you want to traverse all subdirectories when searching Please note that with thousands of filesdirectoriesthis might take a while

SEARCH_TRAVERSE = getattr(settings FILEBROWSER_SEARCH_TRAVERSE False)

DEFAULT_PERMISSIONS

Default upload and version permissions

DEFAULT_PERMISSIONS = getattr(settings FILEBROWSER_DEFAULT_PERMISSIONS 0755)

OVERWRITE_EXISTING

New in version 351

True in order to overwrite existing files False to use the behaviour of the storage engine

OVERWRITE_EXISTING = getattr(settings FILEBROWSER_OVERWRITE_EXISTING True)

12 Settings 9

Django FileBrowser Documentation Release 357

10 Chapter 1 Installation and Setup

CHAPTER 2

API

21 API

211 FileListing

class FileListing(path filter_func=None sorting_by=None sorting_order=None)Returns a list of FileObjects for a server path see FileObject

Parameters

bull path ndash Relative path to a location within sitestoragelocation

bull filter_func ndash Filter function see example below

bull sorting_by ndash Sort the files by any attribute of FileObject

bull sorting_order ndash Sorting order either ldquoascrdquo or ldquodescrdquo

If you want to list all files within a storage location you do

from filebrowsersites import sitefrom filebrowserbase import FileListingfilelisting = FileListing(sitestoragelocation sorting_by=date sorting_order=desc)

Use a custom filter function to limit the list of files

def filter_filelisting(item) item is a FileObjectreturn itemfiletype = Folder

filelisting = FileListing(sitestoragelocation filter_func=filter_listing sorting_by=date sorting_order=desc)

Methods

For the below examples wersquore using this folder-structure

mediauploadstestfoldertestimagejpgmediauploadsblog1imagesblogimagejpg

Note We defined filter_browse as filter_func (see sitespy) And we did not define aVERSIONS_BASEDIR for this demonstration though it is highly recommended to use one

11

Django FileBrowser Documentation Release 357

listing()Returns all items for the given path with oslistdir(path)

gtgtgt for item in filelistinglisting() print itemblogtestfolder

walk()Returns all items for the given path with oswalk(path)

gtgtgt for item in filelistingwalk() print itemblogblog1blog1imagesblog1imagesblogimagejpgblog1imagesblogimage_admin_thumbnailjpgblog1imagesblogimage_mediumjpgblog1imagesblogimage_smalljpgblog1imagesblogimage_thumbnailjpgtestfoldertestfoldertestimagejpg

files_listing_total()Returns a sorted list of FileObjects for listing()

gtgtgt for item in filelistingfiles_listing_total() print itemuploadsbloguploadstestfolder

files_walk_total()Returns a sorted list of FileObjects for walk()

gtgtgt for item in filelistingfiles_walk_total() print itemuploadsbloguploadsblog1uploadsblog1imagesuploadsblog1imagesblogimagejpguploadsblog1imagesblogimage_admin_thumbnailjpguploadsblog1imagesblogimage_mediumjpguploadsblog1imagesblogimage_smalljpguploadsblog1imagesblogimage_thumbnailjpguploadstestfolderuploadstestfoldertestimagejpg

files_listing_filtered()Returns a sorted and filtered list of FileObjects for listing()

gtgtgt for item in filelistingfiles_listing_filtered() print itemuploadsbloguploadstestfolder

files_walk_filtered()Returns a sorted and filtered list of FileObjects for walk()

12 Chapter 2 API

Django FileBrowser Documentation Release 357

gtgtgt for item in filelistingfiles_walk_filtered() print itemuploadsbloguploadsblog1uploadsblog1imagesuploadsblog1imagesblogimagejpguploadstestfolderuploadstestfoldertestimagejpg

Note The versions are not listed (compared with files_walk_total) because of filter_func

results_listing_total()Number of total files based on files_listing_total()

gtgtgt filelistingresults_listing_total()2

results_walk_total()Number of total files based on files_walk_total()

gtgtgt filelistingresults_walk_total()10

results_listing_filtered()Number of filtered files based on files_listing_filtered()

gtgtgt filelistingresults_listing_filtered()2

results_walk_filtered()Number of filtered files based on files_walk_filtered()

gtgtgt filelistingresults_walk_filtered()6

212 FileObject

class FileObject(path site=None)An object representing a media file

Parameters

bull path ndash Relative path to a location within sitestoragelocation

bull site ndash An optional FileBrowser Site

For example

from filebrowsersites import sitefrom filebrowserbase import FileObjectfileobject = FileObject(ospathjoin(sitedirectorytestfoldertestimagejpg))version = FileObject(ospathjoin(fileobjectversions_basedir testfolder testimage_mediumjpg))

21 API 13

Django FileBrowser Documentation Release 357

Attributes

Initial Attributes

pathPath relative to a storage location (including sitedirectory)

gtgtgt fileobjectpathuploadstestfoldertestimagejpg

headThe directory name of pathname path

gtgtgt fileobjectheaduploadstestfolder

filenameName of the file (including the extension) or name of the folder

gtgtgt fileobjectfilenametestimagejpg

filename_lowerLower type of filename

filename_rootFilename without extension

gtgtgt fileobjectfilename_roottestimage

extensionFile extension including the dot With a folder the extensions is None

gtgtgt fileobjectextensionjpg

mimetypeMimetype based on httpdocspythonorglibrarymimetypeshtml

gtgtgt fileobjectmimetype(imagejpeg None)

General Attributes

filetypeType of the file as defined with EXTENSIONS

gtgtgt fileobjectfiletypeImage

filesizeFilesize in Bytes

gtgtgt fileobjectfilesize870037L

14 Chapter 2 API

Django FileBrowser Documentation Release 357

dateDate based on timemktime

gtgtgt fileobjectdate12997603470

datetimeDatetime object

gtgtgt fileobjectdatetimedatetimedatetime(2011 3 10 13 32 27)

existsTrue if the path exists False otherwise

gtgtgt fileobjectexistsTrue

Path and URL attributes

pathPath relative to a storage location (including sitedirectory)

gtgtgt fileobjectpathuploadstestfoldertestimagejpg

path_relative_directoryPath relative to sitedirectory

gtgtgt fileobjectpath_relative_directorytestfoldertestimagejpg

path_fullAbsolute server path (based on storagepath)

gtgtgt fileobjectpath_fullabsolutepathtoserverlocationtestfoldertestimagejpg

dirnameNew in version 34

The directory (not including sitedirectory)

gtgtgt fileobjectdirnametestfolder

urlURL for the filefolder (based on storageurl)

gtgtgt fileobjecturlmediauploadstestfoldertestimagejpg

Image attributes

The image attributes are only useful if the FileObject represents an image

dimensionsImage dimensions as a tuple

21 API 15

Django FileBrowser Documentation Release 357

gtgtgt fileobjectdimensions(1000 750)

widthImage width in px

gtgtgt fileobjectwidth1000

heightImage height in px

gtgtgt fileobjectheight750

aspectratioAspect ratio (float format)

gtgtgt fileobjectaspectratio133534908

orientationImage orientation either Landscape or Portrait

gtgtgt fileobjectorientationLandscape

Folder attributes

The folder attributes make sense when the FileObject represents a directory (not a file)

directory

Deprecated since version 353 Use path_relative_directory instead

folder

Deprecated since version 353 Use dirname instead

is_folderTrue if path is a folder

gtgtgt fileobjectis_folderFalse

is_emptyTrue if the folder is empty False if the folder is not empty or the FileObject is not a folder

gtgtgt fileobjectis_emptyFalse

Version attributes

is_versiontrue if the File is a version of another File

16 Chapter 2 API

Django FileBrowser Documentation Release 357

gtgtgt fileobjectis_versionFalsegtgtgt versionis_versionTrue

versions_basedirThe relative path (from storage location) to the main versions folder Either VERSIONS_BASEDIR orsitedirectory

gtgtgt fileobjectversions_basedir_versionsgtgtgt versionversions_basedir_versions

originalReturns the original FileObject

gtgtgt fileobjectoriginalltFileObject uploadstestfoldertestimagejpggtgtgtgt versionoriginalltFileObject uploadstestfoldertestimagejpggt

original_filenameGet the filename of an original image from a version

gtgtgt fileobjectoriginal_filenametestimagejpggtgtgt versionoriginal_filenametestimagejpg

Methods

Version methods

versions()List all filenames based on VERSIONS

gtgtgt fileobjectversions()[_versionstestfoldertestimage_admin_thumbnailjpg_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionversions()[]

Note The versions are not being generated

admin_versions()List all filenames based on ADMIN_VERSIONS

gtgtgt fileobjectadmin_versions()[_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg

21 API 17

Django FileBrowser Documentation Release 357

_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionadmin_versions()[]

Note The versions are not being generated

version_name(version_suffix)Get the filename for a version

gtgtgt fileobjectversion_name(medium)testimage_mediumjpg

Note The version is not being generated

version_path(version_suffix)Get the path for a version

gtgtgt fileobjectversion_path(medium)_versionstestfoldertestimage_mediumjpg

Note The version is not being generated

version_generate(version_suffix)Generate a version

gtgtgt fileobjectversion_generate(medium)ltFileObject uploadstestfoldertestimage_mediumjpggt

Please note that a version is only generated if it does not already exist or if the original image is newer than theexisting version

Delete methods

delete()Delete the File or Folder from the server

Warning If you delete a Folder all items within the folder are being deleted

delete_versions()Delete all VERSIONS

delete_admin_versions()Delete all ADMIN_VERSIONS

18 Chapter 2 API

CHAPTER 3

Fields amp Widgets

31 Fields amp Widgets

The FileBrowseField is a custom model field which returns a FileObject The widgets FileInput and ClearableFileIn-put are used with the admin app in order to show an additional thumbnail for images

311 FileBrowseField

class FileBrowseField(max_length[ site directory extensions format options])A subclass of CharField referencing a media file within Returns a FileObject

Parameters

bull site ndash A FileBrowser site (defaults to the main site) see FileBrowser Site

bull directory ndash Directory to browse when clicking the search icon

bull extensions ndash List of allowed extensions see Extensions and Formats

bull format ndash A key from SELECT_FORMATS in order to restrict the selection to specificfiletypes see Extensions and Formats

For example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 directory=images extensions=[jpg] blank=True null=True)document = FileBrowseField(PDF max_length=200 directory=documents extensions=[pdfdoc] blank=True null=True)

FileBrowseField in Templates

You can use all attributes from FileObject

blogentryimage ltimg src= publicationimageurl gt

ifequal blogentryimageimage_orientation landscape ltimg src= blogentryimageurl class=landscape gt

endifequal

19

Django FileBrowser Documentation Release 357

Showing Thumbnail in the Changelist

To show a thumbnail with the changelist you can define a ModelAdmin method

from filebrowsersettings import ADMIN_THUMBNAIL

def image_thumbnail(self obj)if objimage and objimagefiletype == Image

return ltimg src=s gt objimageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Using the FileBrowseField with TinyMCE

In order to replace the TinyMCE imagefile manager with the FileBrowser you have to use a FileBrowser CallbackTherersquos an example TinyMCE configuration file in staticjs called TinyMCEAdminjs You can either copy theFileBrowserCallback to your own file or just use tinymce_setupjs (which comes with django-grappelli)

Just add these lines to your ModelAdmin asset definitions

class Mediajs = [pathtotinymcejscriptstiny_mcetiny_mcejs

pathtoyourtinymce_setupjs]

312 FileInput

Subclass of FileInput with an additional thumbnail

from filebrowserwidgets import FileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget FileInput

313 ClearableFileInput

Subclass of ClearableFileInput with an additional thumbnail

from filebrowserwidgets import ClearableFileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget ClearableFileInput

314 Django FileField and the FileBrowser

Return a FileObject from a FileField or ImageField with

20 Chapter 3 Fields amp Widgets

Django FileBrowser Documentation Release 357

from filebrowserbase import FileObject

image_upload = modelsImageField(uImage (Upload) max_length=250 upload_to=image_upload_path blank=True null=True)

def image(self)if selfimage_upload

return FileObject(selfimage_uploadpath)return None

In order show a thumbnail with your changelist you could use a ModelAdmin method

from filebrowserbase import FileObject

def image_thumbnail(self obj)if objimage_upload

image = FileObject(objimage_uploadpath)if imagefiletype == Image

return ltimg src=s gt imageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Note There are different ways to achieve this The above examples show one of several options

31 Fields amp Widgets 21

Django FileBrowser Documentation Release 357

22 Chapter 3 Fields amp Widgets

CHAPTER 4

Admin Interface

41 Admin Interface

The main FileBrowser admin application is an extension for the Django admin interface in order to browser yourmedia folder upload and renamedelete files

411 FileBrowser Site

New in version 340

class FileBrowserSite(name=None app_name=rsquofilebrowserrsquo storage=default_storage)Respresents the FileBrowser admin application (similar to Djangorsquos admin site)

Parameters

bull name ndash A name for the site defaults to None

bull app_name ndash Defaults to lsquofilebrowserrsquo

bull storage ndash A custom storage engine defaults to Djangos default storage

Similar to djangocontribadmin you first need to add a filebrowsersite to your admin interface Inyour urlspy import the default FileBrowser site (or your custom site) and add the site to your URL-patterns (beforeany admin-urls)

from filebrowsersites import site

urlpatterns = patterns(url(r^adminurlfilebrowser include(siteurls))

)

Now you are able to browse the location defined with the storage engine associated to your site

from djangocorefilesstorage import DefaultStoragefrom filebrowsersites import FileBrowserSite

Default FileBrowser sitesite = FileBrowserSite(name=filebrowser storage=DefaultStorage())

My Custom FileBrowser sitecustom_site = FileBrowserSite(name=custom_filebrowser storage=DefaultStorage())custom_sitedirectory = custom_uploads

23

Django FileBrowser Documentation Release 357

Note The module variable site from filebrowsersites is the default FileBrowser application

412 Custom Actions

New in version 340

Similar to Djangorsquos admin actions you can define your FileBrowser actions and thus automate the typical tasks ofyour users Registered custom actions are listed in the detail view of a file and a user can select a single action at atime The selected action will then be applied to the file

The default FileBrowser image actions such as ldquoFlip Verticalrdquo or ldquoRotate 90deg Clockwiserdquo are in fact implemented ascustom actions (see the module filebrowseractions)

Writing Your Own Actions

Custom actions are simple functions

def foo(request fileobjects) Do something with the fileobjects

The first parameter is a HttpRequest object (representing the submitted form in which a user selected the action)and the second parameter is a list of FileObjects to which the action should be applied

The list contains exactly one instance of FileObject (representing the file from the detail view) but this may change inthe future as custom actions may become available also in browse views (similar to admin actions applied to a list ofchecked objects)

Registering an Action

In order to make your action visible you need to register it with a FileBrowser site

siteadd_action(foo)

Once registered the action will appear in the detail view of a file You can also give your action a short description

fooshort_description = Do foo with the File

This short description will then appear in the list of available actions If you do not provide a short description thefunction name will be used instead and FileBrowser will replace any underscores in the function name with spaces

Associating Actions with Specific Files

Each custom action can be associated with a specific file type (eg images audio file etc) to which it applies In orderto do that you need to define a predicatefilter function which takes a single argument (FileObject) and returns Trueif your action is applicable to that FileObject Finally you need to register this filter function with your action

fooapplies_to(lambda fileobject fileobjectfiletype == Image)

In the above example foo will appear in the action list only for image files If you do not specify any filter functionfor your action FileBrowser considers the action as applicable to all files

24 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

Messages amp Intermediate Pages

You can provide a feedback to a user about a successful or failed execution of an action by using a message Forexample

from djangocontrib import messages

def desaturate_image(request fileobjects)for f in fileobjects

Desaturate the imagemessagesadd_message(request messagesSUCCESS _(Image s was desaturated) ffilename)

Some actions may require user confirmation (eg in order to prevent accidental and irreversible modification tofiles) In order to that follow the same pattern as with Djangorsquos admin action and return a HttpResponse objectfrom your action Good practice for intermediate pages is to implement a confirm view and have your action returnHttpResponseRedirect

def crop_image(request fileobjects)files = ampf=join([fpath_relative for f in fileobjects])return HttpResponseRedirect(confirmaction=crop_imageampf=s files)

413 File Storages

New in version 340

You have the option to specify which file storage engine a FileBrowser should use to browseuploadmodify yourmedia files This enables you to use a FileBrowser even if your media files are located at some remote system Seealso the Djangorsquos documentation on storages httpsdocsdjangoprojectcomendevtopicsfiles

To associate a FileBrowser site with a particular storage engine set the storage property of a site object

from djangocorefilesstorage import FileSystemStoragesitestorage = FileSystemStorage(location=pathtomediadirectory base_url=media)

For storage classes other than FileSystemStorage (or those that inherit from that class) therersquos more effort involved inproviding a storage object that can be used with FileBrowser See StorageMixin Class

Note Prior FileBrowser 34 the way to specify FileBrowserlsquos MEDIA_ROOT and MEDIA_URL was via settingspyStarting from version 34 those variables are associated with the storage instance and you can set them as illustratedin the above example

Warning For the reason of backward compatibility FileBrowser settings FILEBROWSER_MEDIA_ROOT andFILEBROWSER_MEDIA_URL can still be used to customize FileBrowser as long as yoursquore using the defaultFileBrowserlsquos site without having changed its storage engine In the next major release of FileBrowser thesesettings will be removed

StorageMixin Class

A FileBrowser uses the Djangorsquos Storage class to access media files However the API of the Storageclass does not provide all methods necessary for FileBrowserrsquos functionality A StorageMixin class fromfilebrowserstorage module therefore defines all the additional methods that a FileBrowser requires

isdir(self name)Returns true if name exists and is a directory

41 Admin Interface 25

Django FileBrowser Documentation Release 357

isfile(self name)Returns true if name exists and is a regular file

move(self old_file_name new_file_name allow_overwrite=False)Moves safely a file from one location to another If allow_ovewrite==False and new_file_nameexists raises an exception

makedirs(self name)Creates all missing directories specified by name Analogue to osmkdirs()

414 Views

All views use the staff_member_requird and path_exists decorator in order to check if the server pathactually exists Some views also use the file_exists decorator

bull Browse fb_browse Browse a directory on your server Returns a FileListing

ndash Optional query string args dir o ot q p filter_date filter_type type

bull Create directory fb_createdir Create a new folder on your server

ndash Optional query string args dir

ndash Signals filebrowser_pre_createdir filebrowser_post_createdir

bull Upload fb_upload Multiple upload

ndash Optional query string args dir type

ndash Signals filebrowser_pre_upload filebrowser_post_upload

bull Edit fb_edit Edit a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_rename filebrowser_post_rename

You are able to apply custom actions (see Custom Actions) to the edit-view

bull Confirm delete fb_confirm_delete Confirm the deletion of a file or folder

ndash Required query string args filename

ndash Optional query string args dir

If you try to delete a folder all filesfolders within this folder are listed on this page

bull Delete fb_delete Delete a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_delete filebrowser_post_delete

Warning If you delete a Folder all items within this Folder are being deleted

bull Version fb_version Generate a version of an image as defined with ADMIN_VERSIONS

ndash Required query string args filename

ndash Optional Query string args dir

This is a helper used by the FileBrowseField and TinyMCE for selecting a version

26 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

415 Signals

The FileBrowser sends a couple of different signals Please take a look at the module filebrowsersignals for furtherexplanation on the provided arguments

bull filebrowser_pre_upload Sent before a an Upload starts

bull filebrowser_post_upload Sent after an Upload has finished

bull filebrowser_pre_delete Sent before an Item (File Folder) is deleted

bull filebrowser_post_delete Sent after an Item (File Folder) has been deleted

bull filebrowser_pre_createdir Sent before a new Folder is created

bull filebrowser_post_createdir Sent after a new Folder has been created

bull filebrowser_pre_rename Sent before an Item (File Folder) is renamed

bull filebrowser_post_rename Sent after an Item (File Folder) has been renamed

bull filebrowser_actions_pre_apply Sent before a custom action is applied

bull filebrowser_actions_post_apply Sent after a custom action has been applied

Example for using these Signals

Herersquos a small example for using the above Signals

from filebrowser import signals

def pre_upload_callback(sender kwargs)Receiver function called before an upload startsprint Pre Upload Callbackprint kwargs kwargs

signalsfilebrowser_pre_uploadconnect(pre_upload_callback)

def post_upload_callback(sender kwargs)Receiver function called each time an upload has finishedprint Post Upload Callbackprint kwargs kwargs You can use all attributes available with the FileObject This is just an example print Filesize kwargs[file]filesizeprint Orientation kwargs[file]orientationprint Extension kwargs[file]extension

signalsfilebrowser_post_uploadconnect(post_upload_callback)

41 Admin Interface 27

Django FileBrowser Documentation Release 357

28 Chapter 4 Admin Interface

CHAPTER 5

Image Versions

51 Versions

With the FileBrowser you are able to define different versionssizes for images This enables you to save an originalimage on your server while having different versions of that image to automatically fit your websites grid Versionsare also useful for responsiveadaptive layouts

511 Defining Versions

New in version 340 methods

First you need to know which versionssizes of an image yoursquod like to generate with your website Letrsquos say yoursquoreusing a 12 column grid with 60px for each column and 20px margin (which is a total of 940px) With this grid youcould (for example) define these image versions

FILEBROWSER_VERSIONS_BASEDIR = _versionsFILEBROWSER_VERSIONS =

admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

Use the methods argument if you need to add a filter

def grayscale(im)Convert image to grayscaleif immode = L

im = imconvert(L)return im

FILEBROWSER_VERSIONS = big verbose_name Big (6 col) width 460 height opts methods [grayscale]

)

29

Django FileBrowser Documentation Release 357

512 Versions and the Admin

When using the FileBrowser with the admin interface you need to define ADMIN_VERSIONS andADMIN_THUMBNAIL (see Settings) ADMIN_VERSIONS are available with the admin ie you are able to seethese versions with the image detail view and you are able to select the versions with the FileBrowseField model field

FILEBROWSER_ADMIN_VERSIONS = [thumbnail small medium big large]FILEBROWSER_ADMIN_THUMBNAIL = admin_thumbnail

513 Versions and the Frontend

With your templates you have two different tags to choose from version and version_object With bothtags the version will be generated if it doesnrsquot already exist OR if the original image is newer than the version Inorder to update an image you just overwrite the original image and the versions will be generated automatically (asyou request them within your template)

A Model example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 blank=True null=True)

With your templates use version if you simply need to retrieve the URL or version_object if you need to geta FileObject

lt-- load filebrowser templatetags --gt load fb_versions

lt-- get the url with version --gtltimg src= version blogentryimage medium gt

lt-- get a fileobject with version_object --gt version_object blogentryimage medium as version_medium version_mediumwidth ltimg src= version_medium gt

Templatetag version

RetrievesGenerates a version and returns an URL

version modelfield_name version_prefix

Templatetag version_object

RetrievesGenerates a version and returns a FileObject

version_object modelfield_name version_prefix as variable

Note With both templatetags version_prefix can either be a string or a variable If version_prefix is astring use quotes

30 Chapter 5 Image Versions

Django FileBrowser Documentation Release 357

514 Versions in Views

If you have a FileObject you can generateretrieve a version with

v = objimageversion_generate(version_prefix) returns a FileObject

515 Placeholder

When developing on a locale machine or a development-server you might not have all the images (resp media-files)available that are on your production instance and downloading these files on a regular basis might not be an option

In that case you can use a placeholder instead of a version You just need to define the PLACEHOLDER and overwritethe settings SHOW_PLACEHOLDER andor FORCE_PLACEHOLDER (see Placeholder)

516 Management Commands

fb_version_generateIf you need to generate certain (or all) versions type

python managepy fb_version_generate

fb_version_removeIf you need to generate certain (or all) versions type

python managepy fb_version_generate

Warning Please be very careful with this command

51 Versions 31

Django FileBrowser Documentation Release 357

32 Chapter 5 Image Versions

CHAPTER 6

Help

61 Help

611 FAQ

Why should I use the FileBrowser

If you need your editors or customers to manage files the FileBrowser is an alternative to an FTP-client Moreoveryou are able to define different image versions according to your websites grid Alternatives to the FileBrowser can befound at httpdjangopackagescomgridsgfile-managers

Do I need Grappelli

Grappelli is a requirement for using the FileBrowser There are several filebrowser-no-grappelli repositories (most ofthem on GitHub) but we donrsquot follow the development

I need help

see Troubleshooting

Why are there no fancy effects

The FileBrowser is about managing files We think that you should prepare your files before uploading them to theserver

How do I upload to another server

Use a custom storage engine see httpsdocsdjangoprojectcomen16howtocustom-file-storage

Why do I need image-versions

You need image-versions if your website is based on a grid

33

Django FileBrowser Documentation Release 357

Is the FileBrowser stable

Wersquove developed the FileBrowser for a couple of years and use it with almost all of our clients That said Grappelli isthe more stable and mature application

How can I contribute

Help is very much needed and appreciated Test the FileBrowser and submit feedbackpatches

Who develops the FileBrowser

The FileBrowser is developed and maintained by Patrick Kranzlmuumlller amp Axel Swoboda of vonautomatisch

612 Troubleshooting

Check your setup

Please check if the problem is caused by your setup

bull Read Quick start guide

bull Check if the staticmedia-files are served correctly

bull Make sure you have removed all custom FileBrowser templates from all locations in TEMPLATE_DIRS orcheck that these templates are compatible with the FileBrowser

Run the tests

Start the shell and type

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Check issues

If your setup is fine please check if your problem is a known issue

bull Take a look at all FileBrowser Issues (incuding closed) and search the FileBrowser Google-Group

Add a ticket

If you think yoursquove found a bug please add a ticket

bull Try to describe your problem as precisely as possible

bull Tell us what you did in order to solve the problem

bull Tell us what version of the FileBrowser you are using

bull Tell us what version of Django you are using

34 Chapter 6 Help

Django FileBrowser Documentation Release 357

bull Please do NOT add tickets if yoursquore having problems with serving staticmedia-files (because this is not relatedto the FileBrowser)

bull Please do NOT add tickets referring to Djangos trunk version

bull At best add a patch

Note Be aware that we may close issues not following these guidlines without further notifications

613 Translation

Translation is done via Transifex

Supported Languages

see httpswwwtransifexnetprojectspdjango-filebrowserresourcedjangopo

614 FileBrowser 35 Release Notes

FileBrowser 35 is compatible with Django 14151617 as well as Grappelli 242526

Update from FileBrowser 34x

bull Update Django to 14151617 and check httpsdocsdjangoprojectcomendevreleases14 orhttpsdocsdjangoprojectcomendevreleases15 or httpsdocsdjangoprojectcomendevreleases16

bull Update Grappelli to 24x25x26x

bull Update FileBrowser to 35x

62 Changelog

621 358 (not yet released)

622 357 (September 10th 2014)

bull New Compatibility with Django 17 and Grappelli 26x

bull Improved Updated tests because of the new random suffix with get_available_name (django storage)

bull Improved Added an icon in order to mark finished uploads

bull Improved Show resulting filename (eg with suffix converted) after successful upload

bull Fixed Permissions with file upload

bull Fixed Unified json response with _upload_file (no matter if file already exists or not)

623 356 (April 16th 2014)

bull Fixed Displaying pagination correctly with lots of entries

62 Changelog 35

Django FileBrowser Documentation Release 357

624 355 (April 13th 2014)

bull New Added client-side (JavaScript) file extension validation to the AJAX uploader

bull New Added experimental Python 33 support

bull Improved Tests with convertnormalize (removed special chars from test filename)

bull Fixed File selection after using search box (CKEditor)

bull Fixed Removed encoding of file URIs with CKEditor

625 354 (February 21st 2014)

bull Fixed Placeholder functionality (including tests)

bull Fixed Convertnormalize filenames (including tests)

bull Fixed Handling uppercase extensions with browse

626 353 (January 7 2014)

bull New added path_full to FileObject

bull Improved added docx to EXTENSIONS

bull Improved Recommend pillow instead of PIL as a requirement

bull Improved Added additional test cases

bull Improved Updated documentation

bull Improved Consistent use of storage (eg storagelocation storageurl)

bull Improved Removed unnecessary functions (eg url_join url_strip)

bull Improved Moved sort_by_attr to FileListing

bull Improved Regex matches with file versions on browse

bull Improved Using djangoconfurls (with djangoconfurlsdefaults as fallback)

bull Improved Adding CONTRIBUTINGrst

bull Improved Removed static Media inner class with fields

bull Improved Removed search icon with fields (has not being used)

bull Improved Added custom class attributes with filebrowser field

bull Improved Updated translations

bull Fixed fixed exception handling with python 25

bull Fixed fixes dir with SEARCH_TRAVERSE true and version select

bull Fixed Make Django FileUploadHandlers work (also fixed a memory leak)

bull Fixed return correct filename with OVERWRITE_EXISTING

bull Fixed fb_version_generate with FILEBROWSER_VERSIONS_BASEDIR

bull Fixed Table sorting with ascdesc

bull Fixed Added DeprecationWarning for FileObjectdirectory and FileObjectfolder

36 Chapter 6 Help

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

ii

Django FileBrowser Documentation Release 357

Media-Management with Grappelli

Note FileBrowser 357 requires Django 141516 or 17 and Grappelli 2425 or 26

Contents 1

Django FileBrowser Documentation Release 357

2 Contents

CHAPTER 1

Installation and Setup

11 Quick start guide

For using the FileBrowser Django needs to be installed and an Admin Site has to be activated

111 Requirements

bull Django 14151617 httpwwwdjangoprojectcom

bull Grappelli 242526 httpsgithubcomsehmaschinedjango-grappelli

bull Pillow httpsgithubcompython-imagingPillow

112 Installation

Install the FileBrowser

pip install django-filebrowser

Add the filebrowser to your INSTALLED_APPS (before djangocontribadmin)

INSTALLED_APPS = (grappellifilebrowserdjangocontribadmin

)

Add the FileBrowser site to your url-patterns (before any admin-urls)

from filebrowsersites import site

urlpatterns = patterns((r^adminfilebrowser include(siteurls))(r^grappelli include(grappelliurls))(r^admin include(adminsiteurls))

)

Collect the static files (please refer to the Staticfiles Documentation for more information)

python managepy collectstatic

3

Django FileBrowser Documentation Release 357

113 Settings

Check the Settings

Note You need to add a folder ldquouploadsrdquo within sitestoragelocation when using the default settingsAnd we strongly recommend to define a VERSIONS_BASEDIR

114 Testing

Run the FileBrowser tests

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Start the devserver and login to your admin site

python managepy runserver ltIP-addressgt8000

Goto adminfilebrowserbrowse and check if everything looksworks as expected If yoursquore having problems seeTroubleshooting

12 Settings

There are some settings in order to customize the FileBrowser Nonetheless you should be able to start with the defaultsettings

All settings can be defined in your projects settings-file In that case you have to use the prefix FILEBROWSER_ forevery setting (eg FILEBROWSER_EXTENSIONS instead of EXTENSIONS)

121 Main URLPaths Settings

MEDIA_ROOT

Warning Will be removed with version 360 Since 34 MEDIA_ROOT is defined with your storage engine

The absolute path to the directory that holds the media-files you want to browse

MEDIA_ROOT = getattr(settings FILEBROWSER_MEDIA_ROOT settingsMEDIA_ROOT)

MEDIA_URL

Warning Will be removed with version 360 Since 34 MEDIA_URL is defined with your storage engine

URL that handles the media served from MEDIA_ROOT

MEDIA_URL = getattr(settings FILEBROWSER_MEDIA_URL settingsMEDIA_URL)

4 Chapter 1 Installation and Setup

Django FileBrowser Documentation Release 357

DIRECTORY (relative to storage location)

Main FileBrowser Directory Leave empty in order to browse all files and folders within a storage location

DIRECTORY = getattr(settings FILEBROWSER_DIRECTORY uploads)

You can override this setting on a perndashsite basis

from filebrowsersites import sitesitedirectory = uploads

122 FileBrowser Media TinyMCE Media

Deprecated since version 353 Use staticfiles instead

123 Extensions and Formats

EXTENSIONS

Allowed extensions for file upload

EXTENSIONS = getattr(settings FILEBROWSER_EXTENSIONS Folder []Image [jpgjpeggifpngtiftiff]Document [pdfdocrtftxtxlscsv]Video [movwmvmpegmpgavirm]Audio [mp3mp4wavaiffmidim4p]

)

SELECT_FORMATS

Set different Options for selecting elements from the FileBrowser

SELECT_FORMATS = getattr(settings FILEBROWSER_SELECT_FORMATS file [FolderImageDocumentVideoAudio]image [Image]document [Document]media [VideoAudio]

)

When using the browse-function for selecting FilesFolders you can use an additional query-attribute type in orderto restrict the choices

124 Versions

VERSIONS_BASEDIR (relative to storage location)

Changed in version 340

Directory to save image versions (and thumbnails) If no directory is given versions are stored at the same location asthe original image

12 Settings 5

Django FileBrowser Documentation Release 357

VERSIONS_BASEDIR = getattr(settings FILEBROWSER_VERSIONS_BASEDIR )

We do recommend the following structure for media files

-- media sitestoragelocation (eg MEDIA_ROOT)-- _versions VERSIONS_BASEDIR (outside of sitedirectory)-- uploads sitedirectory

Warning If VERSIONS_BASEDIR is within sitedirectory it will be browsed

Warning With the next major release (360) the default setting will be ldquo_versionsrdquo

VERSIONS

Define the versions according to your websites grid

VERSIONS = getattr(settings FILEBROWSER_VERSIONS admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

)

VERSION_QUALITY

Quality of saved versions

VERSION_QUALITY = getattr(settings FILEBROWSER_VERSION_QUALITY 90)

ADMIN_VERSIONS

The versions you want to show with the admin interface

ADMIN_VERSIONS = getattr(settings FILEBROWSER_ADMIN_VERSIONS [thumbnail small medium big large])

ADMIN_THUMBNAIL

The version being used as the admin thumbnail

ADMIN_THUMBNAIL = getattr(settings FILEBROWSER_ADMIN_THUMBNAIL admin_thumbnail)

125 Placeholder

With your locale environment you donrsquot necessarily have access to all media files (eg images uploaded by yourclient) Therefore you can use a PLACEHOLDER

6 Chapter 1 Installation and Setup

Django FileBrowser Documentation Release 357

PLACEHOLDER

Path to placeholder image (relative to storage location)

PLACEHOLDER = getattr(settings FILEBROWSER_PLACEHOLDER )

SHOW_PLACEHOLDER

Show placeholder (instead of a version) if the original image does not exist

SHOW_PLACEHOLDER = getattr(settings FILEBROWSER_SHOW_PLACEHOLDER False)

FORCE_PLACEHOLDER

Always show placeholder (even if the original image exists)

FORCE_PLACEHOLDER = getattr(settings FILEBROWSER_FORCE_PLACEHOLDER False)

126 Extra Settings

SAVE_FULL_URL

Deprecated since version 340 With custom storage engines saving the full URL doesnrsquot make sense anymoreMoreover removing this settings allows for easily replacing a FileBrowseField with Djangos File- or ImageField

STRICT_PIL

If set to True the FileBrowser will not try to import a mis-installed PIL

STRICT_PIL = getattr(settings FILEBROWSER_STRICT_PIL False)

IMAGE_MAXBLOCK

see httpmailpythonorgpipermailimage-sig1999-August000816html

IMAGE_MAXBLOCK = getattr(settings FILEBROWSER_IMAGE_MAXBLOCK 10241024)

EXCLUDE

Exclude-patterns for files you donrsquot want to show

EXTENSION_LIST = []for exts in EXTENSIONSvalues()

EXTENSION_LIST += extsEXCLUDE = getattr(settings FILEBROWSER_EXCLUDE (r_((exts)s)__qd13((exts)s) exts (|join(EXTENSION_LIST))))

12 Settings 7

Django FileBrowser Documentation Release 357

MAX_UPLOAD_SIZE

Max Upload Size in Bytes

MAX_UPLOAD_SIZE = getattr(settings FILEBROWSER_MAX_UPLOAD_SIZE 10485760)

NORMALIZE_FILENAME

True if you want to normalize filename on upload and remove all non-alphanumeric characters (except for under-scores spaces amp dashes)

NORMALIZE_FILENAME = getattr(settings FILEBROWSER_NORMALIZE_FILENAME False)

CONVERT_FILENAME

True if you want to convert the filename on upload (replace spaces and convert to lowercase)

CONVERT_FILENAME = getattr(settings FILEBROWSER_CONVERT_FILENAME True)

LIST_PER_PAGE

How many items appear on each paginated list

LIST_PER_PAGE = getattr(settings FILEBROWSER_LIST_PER_PAGE 50)

DEFAULT_SORTING_BY

Default sorting attribute

DEFAULT_SORTING_BY = getattr(settings FILEBROWSER_DEFAULT_SORTING_BY date)

Options are date filesize filename_lower filetype_checked

DEFAULT_SORTING_ORDER

Default sorting order

DEFAULT_SORTING_ORDER = getattr(settings FILEBROWSER_DEFAULT_SORTING_ORDER desc)

Options are asc or desc

FOLDER_REGEX

regex to clean directory names before creation

FOLDER_REGEX = getattr(settings FILEBROWSER_FOLDER_REGEX r^[w_ -]+$)

8 Chapter 1 Installation and Setup

Django FileBrowser Documentation Release 357

SEARCH_TRAVERSE

True if you want to traverse all subdirectories when searching Please note that with thousands of filesdirectoriesthis might take a while

SEARCH_TRAVERSE = getattr(settings FILEBROWSER_SEARCH_TRAVERSE False)

DEFAULT_PERMISSIONS

Default upload and version permissions

DEFAULT_PERMISSIONS = getattr(settings FILEBROWSER_DEFAULT_PERMISSIONS 0755)

OVERWRITE_EXISTING

New in version 351

True in order to overwrite existing files False to use the behaviour of the storage engine

OVERWRITE_EXISTING = getattr(settings FILEBROWSER_OVERWRITE_EXISTING True)

12 Settings 9

Django FileBrowser Documentation Release 357

10 Chapter 1 Installation and Setup

CHAPTER 2

API

21 API

211 FileListing

class FileListing(path filter_func=None sorting_by=None sorting_order=None)Returns a list of FileObjects for a server path see FileObject

Parameters

bull path ndash Relative path to a location within sitestoragelocation

bull filter_func ndash Filter function see example below

bull sorting_by ndash Sort the files by any attribute of FileObject

bull sorting_order ndash Sorting order either ldquoascrdquo or ldquodescrdquo

If you want to list all files within a storage location you do

from filebrowsersites import sitefrom filebrowserbase import FileListingfilelisting = FileListing(sitestoragelocation sorting_by=date sorting_order=desc)

Use a custom filter function to limit the list of files

def filter_filelisting(item) item is a FileObjectreturn itemfiletype = Folder

filelisting = FileListing(sitestoragelocation filter_func=filter_listing sorting_by=date sorting_order=desc)

Methods

For the below examples wersquore using this folder-structure

mediauploadstestfoldertestimagejpgmediauploadsblog1imagesblogimagejpg

Note We defined filter_browse as filter_func (see sitespy) And we did not define aVERSIONS_BASEDIR for this demonstration though it is highly recommended to use one

11

Django FileBrowser Documentation Release 357

listing()Returns all items for the given path with oslistdir(path)

gtgtgt for item in filelistinglisting() print itemblogtestfolder

walk()Returns all items for the given path with oswalk(path)

gtgtgt for item in filelistingwalk() print itemblogblog1blog1imagesblog1imagesblogimagejpgblog1imagesblogimage_admin_thumbnailjpgblog1imagesblogimage_mediumjpgblog1imagesblogimage_smalljpgblog1imagesblogimage_thumbnailjpgtestfoldertestfoldertestimagejpg

files_listing_total()Returns a sorted list of FileObjects for listing()

gtgtgt for item in filelistingfiles_listing_total() print itemuploadsbloguploadstestfolder

files_walk_total()Returns a sorted list of FileObjects for walk()

gtgtgt for item in filelistingfiles_walk_total() print itemuploadsbloguploadsblog1uploadsblog1imagesuploadsblog1imagesblogimagejpguploadsblog1imagesblogimage_admin_thumbnailjpguploadsblog1imagesblogimage_mediumjpguploadsblog1imagesblogimage_smalljpguploadsblog1imagesblogimage_thumbnailjpguploadstestfolderuploadstestfoldertestimagejpg

files_listing_filtered()Returns a sorted and filtered list of FileObjects for listing()

gtgtgt for item in filelistingfiles_listing_filtered() print itemuploadsbloguploadstestfolder

files_walk_filtered()Returns a sorted and filtered list of FileObjects for walk()

12 Chapter 2 API

Django FileBrowser Documentation Release 357

gtgtgt for item in filelistingfiles_walk_filtered() print itemuploadsbloguploadsblog1uploadsblog1imagesuploadsblog1imagesblogimagejpguploadstestfolderuploadstestfoldertestimagejpg

Note The versions are not listed (compared with files_walk_total) because of filter_func

results_listing_total()Number of total files based on files_listing_total()

gtgtgt filelistingresults_listing_total()2

results_walk_total()Number of total files based on files_walk_total()

gtgtgt filelistingresults_walk_total()10

results_listing_filtered()Number of filtered files based on files_listing_filtered()

gtgtgt filelistingresults_listing_filtered()2

results_walk_filtered()Number of filtered files based on files_walk_filtered()

gtgtgt filelistingresults_walk_filtered()6

212 FileObject

class FileObject(path site=None)An object representing a media file

Parameters

bull path ndash Relative path to a location within sitestoragelocation

bull site ndash An optional FileBrowser Site

For example

from filebrowsersites import sitefrom filebrowserbase import FileObjectfileobject = FileObject(ospathjoin(sitedirectorytestfoldertestimagejpg))version = FileObject(ospathjoin(fileobjectversions_basedir testfolder testimage_mediumjpg))

21 API 13

Django FileBrowser Documentation Release 357

Attributes

Initial Attributes

pathPath relative to a storage location (including sitedirectory)

gtgtgt fileobjectpathuploadstestfoldertestimagejpg

headThe directory name of pathname path

gtgtgt fileobjectheaduploadstestfolder

filenameName of the file (including the extension) or name of the folder

gtgtgt fileobjectfilenametestimagejpg

filename_lowerLower type of filename

filename_rootFilename without extension

gtgtgt fileobjectfilename_roottestimage

extensionFile extension including the dot With a folder the extensions is None

gtgtgt fileobjectextensionjpg

mimetypeMimetype based on httpdocspythonorglibrarymimetypeshtml

gtgtgt fileobjectmimetype(imagejpeg None)

General Attributes

filetypeType of the file as defined with EXTENSIONS

gtgtgt fileobjectfiletypeImage

filesizeFilesize in Bytes

gtgtgt fileobjectfilesize870037L

14 Chapter 2 API

Django FileBrowser Documentation Release 357

dateDate based on timemktime

gtgtgt fileobjectdate12997603470

datetimeDatetime object

gtgtgt fileobjectdatetimedatetimedatetime(2011 3 10 13 32 27)

existsTrue if the path exists False otherwise

gtgtgt fileobjectexistsTrue

Path and URL attributes

pathPath relative to a storage location (including sitedirectory)

gtgtgt fileobjectpathuploadstestfoldertestimagejpg

path_relative_directoryPath relative to sitedirectory

gtgtgt fileobjectpath_relative_directorytestfoldertestimagejpg

path_fullAbsolute server path (based on storagepath)

gtgtgt fileobjectpath_fullabsolutepathtoserverlocationtestfoldertestimagejpg

dirnameNew in version 34

The directory (not including sitedirectory)

gtgtgt fileobjectdirnametestfolder

urlURL for the filefolder (based on storageurl)

gtgtgt fileobjecturlmediauploadstestfoldertestimagejpg

Image attributes

The image attributes are only useful if the FileObject represents an image

dimensionsImage dimensions as a tuple

21 API 15

Django FileBrowser Documentation Release 357

gtgtgt fileobjectdimensions(1000 750)

widthImage width in px

gtgtgt fileobjectwidth1000

heightImage height in px

gtgtgt fileobjectheight750

aspectratioAspect ratio (float format)

gtgtgt fileobjectaspectratio133534908

orientationImage orientation either Landscape or Portrait

gtgtgt fileobjectorientationLandscape

Folder attributes

The folder attributes make sense when the FileObject represents a directory (not a file)

directory

Deprecated since version 353 Use path_relative_directory instead

folder

Deprecated since version 353 Use dirname instead

is_folderTrue if path is a folder

gtgtgt fileobjectis_folderFalse

is_emptyTrue if the folder is empty False if the folder is not empty or the FileObject is not a folder

gtgtgt fileobjectis_emptyFalse

Version attributes

is_versiontrue if the File is a version of another File

16 Chapter 2 API

Django FileBrowser Documentation Release 357

gtgtgt fileobjectis_versionFalsegtgtgt versionis_versionTrue

versions_basedirThe relative path (from storage location) to the main versions folder Either VERSIONS_BASEDIR orsitedirectory

gtgtgt fileobjectversions_basedir_versionsgtgtgt versionversions_basedir_versions

originalReturns the original FileObject

gtgtgt fileobjectoriginalltFileObject uploadstestfoldertestimagejpggtgtgtgt versionoriginalltFileObject uploadstestfoldertestimagejpggt

original_filenameGet the filename of an original image from a version

gtgtgt fileobjectoriginal_filenametestimagejpggtgtgt versionoriginal_filenametestimagejpg

Methods

Version methods

versions()List all filenames based on VERSIONS

gtgtgt fileobjectversions()[_versionstestfoldertestimage_admin_thumbnailjpg_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionversions()[]

Note The versions are not being generated

admin_versions()List all filenames based on ADMIN_VERSIONS

gtgtgt fileobjectadmin_versions()[_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg

21 API 17

Django FileBrowser Documentation Release 357

_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionadmin_versions()[]

Note The versions are not being generated

version_name(version_suffix)Get the filename for a version

gtgtgt fileobjectversion_name(medium)testimage_mediumjpg

Note The version is not being generated

version_path(version_suffix)Get the path for a version

gtgtgt fileobjectversion_path(medium)_versionstestfoldertestimage_mediumjpg

Note The version is not being generated

version_generate(version_suffix)Generate a version

gtgtgt fileobjectversion_generate(medium)ltFileObject uploadstestfoldertestimage_mediumjpggt

Please note that a version is only generated if it does not already exist or if the original image is newer than theexisting version

Delete methods

delete()Delete the File or Folder from the server

Warning If you delete a Folder all items within the folder are being deleted

delete_versions()Delete all VERSIONS

delete_admin_versions()Delete all ADMIN_VERSIONS

18 Chapter 2 API

CHAPTER 3

Fields amp Widgets

31 Fields amp Widgets

The FileBrowseField is a custom model field which returns a FileObject The widgets FileInput and ClearableFileIn-put are used with the admin app in order to show an additional thumbnail for images

311 FileBrowseField

class FileBrowseField(max_length[ site directory extensions format options])A subclass of CharField referencing a media file within Returns a FileObject

Parameters

bull site ndash A FileBrowser site (defaults to the main site) see FileBrowser Site

bull directory ndash Directory to browse when clicking the search icon

bull extensions ndash List of allowed extensions see Extensions and Formats

bull format ndash A key from SELECT_FORMATS in order to restrict the selection to specificfiletypes see Extensions and Formats

For example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 directory=images extensions=[jpg] blank=True null=True)document = FileBrowseField(PDF max_length=200 directory=documents extensions=[pdfdoc] blank=True null=True)

FileBrowseField in Templates

You can use all attributes from FileObject

blogentryimage ltimg src= publicationimageurl gt

ifequal blogentryimageimage_orientation landscape ltimg src= blogentryimageurl class=landscape gt

endifequal

19

Django FileBrowser Documentation Release 357

Showing Thumbnail in the Changelist

To show a thumbnail with the changelist you can define a ModelAdmin method

from filebrowsersettings import ADMIN_THUMBNAIL

def image_thumbnail(self obj)if objimage and objimagefiletype == Image

return ltimg src=s gt objimageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Using the FileBrowseField with TinyMCE

In order to replace the TinyMCE imagefile manager with the FileBrowser you have to use a FileBrowser CallbackTherersquos an example TinyMCE configuration file in staticjs called TinyMCEAdminjs You can either copy theFileBrowserCallback to your own file or just use tinymce_setupjs (which comes with django-grappelli)

Just add these lines to your ModelAdmin asset definitions

class Mediajs = [pathtotinymcejscriptstiny_mcetiny_mcejs

pathtoyourtinymce_setupjs]

312 FileInput

Subclass of FileInput with an additional thumbnail

from filebrowserwidgets import FileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget FileInput

313 ClearableFileInput

Subclass of ClearableFileInput with an additional thumbnail

from filebrowserwidgets import ClearableFileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget ClearableFileInput

314 Django FileField and the FileBrowser

Return a FileObject from a FileField or ImageField with

20 Chapter 3 Fields amp Widgets

Django FileBrowser Documentation Release 357

from filebrowserbase import FileObject

image_upload = modelsImageField(uImage (Upload) max_length=250 upload_to=image_upload_path blank=True null=True)

def image(self)if selfimage_upload

return FileObject(selfimage_uploadpath)return None

In order show a thumbnail with your changelist you could use a ModelAdmin method

from filebrowserbase import FileObject

def image_thumbnail(self obj)if objimage_upload

image = FileObject(objimage_uploadpath)if imagefiletype == Image

return ltimg src=s gt imageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Note There are different ways to achieve this The above examples show one of several options

31 Fields amp Widgets 21

Django FileBrowser Documentation Release 357

22 Chapter 3 Fields amp Widgets

CHAPTER 4

Admin Interface

41 Admin Interface

The main FileBrowser admin application is an extension for the Django admin interface in order to browser yourmedia folder upload and renamedelete files

411 FileBrowser Site

New in version 340

class FileBrowserSite(name=None app_name=rsquofilebrowserrsquo storage=default_storage)Respresents the FileBrowser admin application (similar to Djangorsquos admin site)

Parameters

bull name ndash A name for the site defaults to None

bull app_name ndash Defaults to lsquofilebrowserrsquo

bull storage ndash A custom storage engine defaults to Djangos default storage

Similar to djangocontribadmin you first need to add a filebrowsersite to your admin interface Inyour urlspy import the default FileBrowser site (or your custom site) and add the site to your URL-patterns (beforeany admin-urls)

from filebrowsersites import site

urlpatterns = patterns(url(r^adminurlfilebrowser include(siteurls))

)

Now you are able to browse the location defined with the storage engine associated to your site

from djangocorefilesstorage import DefaultStoragefrom filebrowsersites import FileBrowserSite

Default FileBrowser sitesite = FileBrowserSite(name=filebrowser storage=DefaultStorage())

My Custom FileBrowser sitecustom_site = FileBrowserSite(name=custom_filebrowser storage=DefaultStorage())custom_sitedirectory = custom_uploads

23

Django FileBrowser Documentation Release 357

Note The module variable site from filebrowsersites is the default FileBrowser application

412 Custom Actions

New in version 340

Similar to Djangorsquos admin actions you can define your FileBrowser actions and thus automate the typical tasks ofyour users Registered custom actions are listed in the detail view of a file and a user can select a single action at atime The selected action will then be applied to the file

The default FileBrowser image actions such as ldquoFlip Verticalrdquo or ldquoRotate 90deg Clockwiserdquo are in fact implemented ascustom actions (see the module filebrowseractions)

Writing Your Own Actions

Custom actions are simple functions

def foo(request fileobjects) Do something with the fileobjects

The first parameter is a HttpRequest object (representing the submitted form in which a user selected the action)and the second parameter is a list of FileObjects to which the action should be applied

The list contains exactly one instance of FileObject (representing the file from the detail view) but this may change inthe future as custom actions may become available also in browse views (similar to admin actions applied to a list ofchecked objects)

Registering an Action

In order to make your action visible you need to register it with a FileBrowser site

siteadd_action(foo)

Once registered the action will appear in the detail view of a file You can also give your action a short description

fooshort_description = Do foo with the File

This short description will then appear in the list of available actions If you do not provide a short description thefunction name will be used instead and FileBrowser will replace any underscores in the function name with spaces

Associating Actions with Specific Files

Each custom action can be associated with a specific file type (eg images audio file etc) to which it applies In orderto do that you need to define a predicatefilter function which takes a single argument (FileObject) and returns Trueif your action is applicable to that FileObject Finally you need to register this filter function with your action

fooapplies_to(lambda fileobject fileobjectfiletype == Image)

In the above example foo will appear in the action list only for image files If you do not specify any filter functionfor your action FileBrowser considers the action as applicable to all files

24 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

Messages amp Intermediate Pages

You can provide a feedback to a user about a successful or failed execution of an action by using a message Forexample

from djangocontrib import messages

def desaturate_image(request fileobjects)for f in fileobjects

Desaturate the imagemessagesadd_message(request messagesSUCCESS _(Image s was desaturated) ffilename)

Some actions may require user confirmation (eg in order to prevent accidental and irreversible modification tofiles) In order to that follow the same pattern as with Djangorsquos admin action and return a HttpResponse objectfrom your action Good practice for intermediate pages is to implement a confirm view and have your action returnHttpResponseRedirect

def crop_image(request fileobjects)files = ampf=join([fpath_relative for f in fileobjects])return HttpResponseRedirect(confirmaction=crop_imageampf=s files)

413 File Storages

New in version 340

You have the option to specify which file storage engine a FileBrowser should use to browseuploadmodify yourmedia files This enables you to use a FileBrowser even if your media files are located at some remote system Seealso the Djangorsquos documentation on storages httpsdocsdjangoprojectcomendevtopicsfiles

To associate a FileBrowser site with a particular storage engine set the storage property of a site object

from djangocorefilesstorage import FileSystemStoragesitestorage = FileSystemStorage(location=pathtomediadirectory base_url=media)

For storage classes other than FileSystemStorage (or those that inherit from that class) therersquos more effort involved inproviding a storage object that can be used with FileBrowser See StorageMixin Class

Note Prior FileBrowser 34 the way to specify FileBrowserlsquos MEDIA_ROOT and MEDIA_URL was via settingspyStarting from version 34 those variables are associated with the storage instance and you can set them as illustratedin the above example

Warning For the reason of backward compatibility FileBrowser settings FILEBROWSER_MEDIA_ROOT andFILEBROWSER_MEDIA_URL can still be used to customize FileBrowser as long as yoursquore using the defaultFileBrowserlsquos site without having changed its storage engine In the next major release of FileBrowser thesesettings will be removed

StorageMixin Class

A FileBrowser uses the Djangorsquos Storage class to access media files However the API of the Storageclass does not provide all methods necessary for FileBrowserrsquos functionality A StorageMixin class fromfilebrowserstorage module therefore defines all the additional methods that a FileBrowser requires

isdir(self name)Returns true if name exists and is a directory

41 Admin Interface 25

Django FileBrowser Documentation Release 357

isfile(self name)Returns true if name exists and is a regular file

move(self old_file_name new_file_name allow_overwrite=False)Moves safely a file from one location to another If allow_ovewrite==False and new_file_nameexists raises an exception

makedirs(self name)Creates all missing directories specified by name Analogue to osmkdirs()

414 Views

All views use the staff_member_requird and path_exists decorator in order to check if the server pathactually exists Some views also use the file_exists decorator

bull Browse fb_browse Browse a directory on your server Returns a FileListing

ndash Optional query string args dir o ot q p filter_date filter_type type

bull Create directory fb_createdir Create a new folder on your server

ndash Optional query string args dir

ndash Signals filebrowser_pre_createdir filebrowser_post_createdir

bull Upload fb_upload Multiple upload

ndash Optional query string args dir type

ndash Signals filebrowser_pre_upload filebrowser_post_upload

bull Edit fb_edit Edit a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_rename filebrowser_post_rename

You are able to apply custom actions (see Custom Actions) to the edit-view

bull Confirm delete fb_confirm_delete Confirm the deletion of a file or folder

ndash Required query string args filename

ndash Optional query string args dir

If you try to delete a folder all filesfolders within this folder are listed on this page

bull Delete fb_delete Delete a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_delete filebrowser_post_delete

Warning If you delete a Folder all items within this Folder are being deleted

bull Version fb_version Generate a version of an image as defined with ADMIN_VERSIONS

ndash Required query string args filename

ndash Optional Query string args dir

This is a helper used by the FileBrowseField and TinyMCE for selecting a version

26 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

415 Signals

The FileBrowser sends a couple of different signals Please take a look at the module filebrowsersignals for furtherexplanation on the provided arguments

bull filebrowser_pre_upload Sent before a an Upload starts

bull filebrowser_post_upload Sent after an Upload has finished

bull filebrowser_pre_delete Sent before an Item (File Folder) is deleted

bull filebrowser_post_delete Sent after an Item (File Folder) has been deleted

bull filebrowser_pre_createdir Sent before a new Folder is created

bull filebrowser_post_createdir Sent after a new Folder has been created

bull filebrowser_pre_rename Sent before an Item (File Folder) is renamed

bull filebrowser_post_rename Sent after an Item (File Folder) has been renamed

bull filebrowser_actions_pre_apply Sent before a custom action is applied

bull filebrowser_actions_post_apply Sent after a custom action has been applied

Example for using these Signals

Herersquos a small example for using the above Signals

from filebrowser import signals

def pre_upload_callback(sender kwargs)Receiver function called before an upload startsprint Pre Upload Callbackprint kwargs kwargs

signalsfilebrowser_pre_uploadconnect(pre_upload_callback)

def post_upload_callback(sender kwargs)Receiver function called each time an upload has finishedprint Post Upload Callbackprint kwargs kwargs You can use all attributes available with the FileObject This is just an example print Filesize kwargs[file]filesizeprint Orientation kwargs[file]orientationprint Extension kwargs[file]extension

signalsfilebrowser_post_uploadconnect(post_upload_callback)

41 Admin Interface 27

Django FileBrowser Documentation Release 357

28 Chapter 4 Admin Interface

CHAPTER 5

Image Versions

51 Versions

With the FileBrowser you are able to define different versionssizes for images This enables you to save an originalimage on your server while having different versions of that image to automatically fit your websites grid Versionsare also useful for responsiveadaptive layouts

511 Defining Versions

New in version 340 methods

First you need to know which versionssizes of an image yoursquod like to generate with your website Letrsquos say yoursquoreusing a 12 column grid with 60px for each column and 20px margin (which is a total of 940px) With this grid youcould (for example) define these image versions

FILEBROWSER_VERSIONS_BASEDIR = _versionsFILEBROWSER_VERSIONS =

admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

Use the methods argument if you need to add a filter

def grayscale(im)Convert image to grayscaleif immode = L

im = imconvert(L)return im

FILEBROWSER_VERSIONS = big verbose_name Big (6 col) width 460 height opts methods [grayscale]

)

29

Django FileBrowser Documentation Release 357

512 Versions and the Admin

When using the FileBrowser with the admin interface you need to define ADMIN_VERSIONS andADMIN_THUMBNAIL (see Settings) ADMIN_VERSIONS are available with the admin ie you are able to seethese versions with the image detail view and you are able to select the versions with the FileBrowseField model field

FILEBROWSER_ADMIN_VERSIONS = [thumbnail small medium big large]FILEBROWSER_ADMIN_THUMBNAIL = admin_thumbnail

513 Versions and the Frontend

With your templates you have two different tags to choose from version and version_object With bothtags the version will be generated if it doesnrsquot already exist OR if the original image is newer than the version Inorder to update an image you just overwrite the original image and the versions will be generated automatically (asyou request them within your template)

A Model example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 blank=True null=True)

With your templates use version if you simply need to retrieve the URL or version_object if you need to geta FileObject

lt-- load filebrowser templatetags --gt load fb_versions

lt-- get the url with version --gtltimg src= version blogentryimage medium gt

lt-- get a fileobject with version_object --gt version_object blogentryimage medium as version_medium version_mediumwidth ltimg src= version_medium gt

Templatetag version

RetrievesGenerates a version and returns an URL

version modelfield_name version_prefix

Templatetag version_object

RetrievesGenerates a version and returns a FileObject

version_object modelfield_name version_prefix as variable

Note With both templatetags version_prefix can either be a string or a variable If version_prefix is astring use quotes

30 Chapter 5 Image Versions

Django FileBrowser Documentation Release 357

514 Versions in Views

If you have a FileObject you can generateretrieve a version with

v = objimageversion_generate(version_prefix) returns a FileObject

515 Placeholder

When developing on a locale machine or a development-server you might not have all the images (resp media-files)available that are on your production instance and downloading these files on a regular basis might not be an option

In that case you can use a placeholder instead of a version You just need to define the PLACEHOLDER and overwritethe settings SHOW_PLACEHOLDER andor FORCE_PLACEHOLDER (see Placeholder)

516 Management Commands

fb_version_generateIf you need to generate certain (or all) versions type

python managepy fb_version_generate

fb_version_removeIf you need to generate certain (or all) versions type

python managepy fb_version_generate

Warning Please be very careful with this command

51 Versions 31

Django FileBrowser Documentation Release 357

32 Chapter 5 Image Versions

CHAPTER 6

Help

61 Help

611 FAQ

Why should I use the FileBrowser

If you need your editors or customers to manage files the FileBrowser is an alternative to an FTP-client Moreoveryou are able to define different image versions according to your websites grid Alternatives to the FileBrowser can befound at httpdjangopackagescomgridsgfile-managers

Do I need Grappelli

Grappelli is a requirement for using the FileBrowser There are several filebrowser-no-grappelli repositories (most ofthem on GitHub) but we donrsquot follow the development

I need help

see Troubleshooting

Why are there no fancy effects

The FileBrowser is about managing files We think that you should prepare your files before uploading them to theserver

How do I upload to another server

Use a custom storage engine see httpsdocsdjangoprojectcomen16howtocustom-file-storage

Why do I need image-versions

You need image-versions if your website is based on a grid

33

Django FileBrowser Documentation Release 357

Is the FileBrowser stable

Wersquove developed the FileBrowser for a couple of years and use it with almost all of our clients That said Grappelli isthe more stable and mature application

How can I contribute

Help is very much needed and appreciated Test the FileBrowser and submit feedbackpatches

Who develops the FileBrowser

The FileBrowser is developed and maintained by Patrick Kranzlmuumlller amp Axel Swoboda of vonautomatisch

612 Troubleshooting

Check your setup

Please check if the problem is caused by your setup

bull Read Quick start guide

bull Check if the staticmedia-files are served correctly

bull Make sure you have removed all custom FileBrowser templates from all locations in TEMPLATE_DIRS orcheck that these templates are compatible with the FileBrowser

Run the tests

Start the shell and type

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Check issues

If your setup is fine please check if your problem is a known issue

bull Take a look at all FileBrowser Issues (incuding closed) and search the FileBrowser Google-Group

Add a ticket

If you think yoursquove found a bug please add a ticket

bull Try to describe your problem as precisely as possible

bull Tell us what you did in order to solve the problem

bull Tell us what version of the FileBrowser you are using

bull Tell us what version of Django you are using

34 Chapter 6 Help

Django FileBrowser Documentation Release 357

bull Please do NOT add tickets if yoursquore having problems with serving staticmedia-files (because this is not relatedto the FileBrowser)

bull Please do NOT add tickets referring to Djangos trunk version

bull At best add a patch

Note Be aware that we may close issues not following these guidlines without further notifications

613 Translation

Translation is done via Transifex

Supported Languages

see httpswwwtransifexnetprojectspdjango-filebrowserresourcedjangopo

614 FileBrowser 35 Release Notes

FileBrowser 35 is compatible with Django 14151617 as well as Grappelli 242526

Update from FileBrowser 34x

bull Update Django to 14151617 and check httpsdocsdjangoprojectcomendevreleases14 orhttpsdocsdjangoprojectcomendevreleases15 or httpsdocsdjangoprojectcomendevreleases16

bull Update Grappelli to 24x25x26x

bull Update FileBrowser to 35x

62 Changelog

621 358 (not yet released)

622 357 (September 10th 2014)

bull New Compatibility with Django 17 and Grappelli 26x

bull Improved Updated tests because of the new random suffix with get_available_name (django storage)

bull Improved Added an icon in order to mark finished uploads

bull Improved Show resulting filename (eg with suffix converted) after successful upload

bull Fixed Permissions with file upload

bull Fixed Unified json response with _upload_file (no matter if file already exists or not)

623 356 (April 16th 2014)

bull Fixed Displaying pagination correctly with lots of entries

62 Changelog 35

Django FileBrowser Documentation Release 357

624 355 (April 13th 2014)

bull New Added client-side (JavaScript) file extension validation to the AJAX uploader

bull New Added experimental Python 33 support

bull Improved Tests with convertnormalize (removed special chars from test filename)

bull Fixed File selection after using search box (CKEditor)

bull Fixed Removed encoding of file URIs with CKEditor

625 354 (February 21st 2014)

bull Fixed Placeholder functionality (including tests)

bull Fixed Convertnormalize filenames (including tests)

bull Fixed Handling uppercase extensions with browse

626 353 (January 7 2014)

bull New added path_full to FileObject

bull Improved added docx to EXTENSIONS

bull Improved Recommend pillow instead of PIL as a requirement

bull Improved Added additional test cases

bull Improved Updated documentation

bull Improved Consistent use of storage (eg storagelocation storageurl)

bull Improved Removed unnecessary functions (eg url_join url_strip)

bull Improved Moved sort_by_attr to FileListing

bull Improved Regex matches with file versions on browse

bull Improved Using djangoconfurls (with djangoconfurlsdefaults as fallback)

bull Improved Adding CONTRIBUTINGrst

bull Improved Removed static Media inner class with fields

bull Improved Removed search icon with fields (has not being used)

bull Improved Added custom class attributes with filebrowser field

bull Improved Updated translations

bull Fixed fixed exception handling with python 25

bull Fixed fixes dir with SEARCH_TRAVERSE true and version select

bull Fixed Make Django FileUploadHandlers work (also fixed a memory leak)

bull Fixed return correct filename with OVERWRITE_EXISTING

bull Fixed fb_version_generate with FILEBROWSER_VERSIONS_BASEDIR

bull Fixed Table sorting with ascdesc

bull Fixed Added DeprecationWarning for FileObjectdirectory and FileObjectfolder

36 Chapter 6 Help

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

Django FileBrowser Documentation Release 357

Media-Management with Grappelli

Note FileBrowser 357 requires Django 141516 or 17 and Grappelli 2425 or 26

Contents 1

Django FileBrowser Documentation Release 357

2 Contents

CHAPTER 1

Installation and Setup

11 Quick start guide

For using the FileBrowser Django needs to be installed and an Admin Site has to be activated

111 Requirements

bull Django 14151617 httpwwwdjangoprojectcom

bull Grappelli 242526 httpsgithubcomsehmaschinedjango-grappelli

bull Pillow httpsgithubcompython-imagingPillow

112 Installation

Install the FileBrowser

pip install django-filebrowser

Add the filebrowser to your INSTALLED_APPS (before djangocontribadmin)

INSTALLED_APPS = (grappellifilebrowserdjangocontribadmin

)

Add the FileBrowser site to your url-patterns (before any admin-urls)

from filebrowsersites import site

urlpatterns = patterns((r^adminfilebrowser include(siteurls))(r^grappelli include(grappelliurls))(r^admin include(adminsiteurls))

)

Collect the static files (please refer to the Staticfiles Documentation for more information)

python managepy collectstatic

3

Django FileBrowser Documentation Release 357

113 Settings

Check the Settings

Note You need to add a folder ldquouploadsrdquo within sitestoragelocation when using the default settingsAnd we strongly recommend to define a VERSIONS_BASEDIR

114 Testing

Run the FileBrowser tests

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Start the devserver and login to your admin site

python managepy runserver ltIP-addressgt8000

Goto adminfilebrowserbrowse and check if everything looksworks as expected If yoursquore having problems seeTroubleshooting

12 Settings

There are some settings in order to customize the FileBrowser Nonetheless you should be able to start with the defaultsettings

All settings can be defined in your projects settings-file In that case you have to use the prefix FILEBROWSER_ forevery setting (eg FILEBROWSER_EXTENSIONS instead of EXTENSIONS)

121 Main URLPaths Settings

MEDIA_ROOT

Warning Will be removed with version 360 Since 34 MEDIA_ROOT is defined with your storage engine

The absolute path to the directory that holds the media-files you want to browse

MEDIA_ROOT = getattr(settings FILEBROWSER_MEDIA_ROOT settingsMEDIA_ROOT)

MEDIA_URL

Warning Will be removed with version 360 Since 34 MEDIA_URL is defined with your storage engine

URL that handles the media served from MEDIA_ROOT

MEDIA_URL = getattr(settings FILEBROWSER_MEDIA_URL settingsMEDIA_URL)

4 Chapter 1 Installation and Setup

Django FileBrowser Documentation Release 357

DIRECTORY (relative to storage location)

Main FileBrowser Directory Leave empty in order to browse all files and folders within a storage location

DIRECTORY = getattr(settings FILEBROWSER_DIRECTORY uploads)

You can override this setting on a perndashsite basis

from filebrowsersites import sitesitedirectory = uploads

122 FileBrowser Media TinyMCE Media

Deprecated since version 353 Use staticfiles instead

123 Extensions and Formats

EXTENSIONS

Allowed extensions for file upload

EXTENSIONS = getattr(settings FILEBROWSER_EXTENSIONS Folder []Image [jpgjpeggifpngtiftiff]Document [pdfdocrtftxtxlscsv]Video [movwmvmpegmpgavirm]Audio [mp3mp4wavaiffmidim4p]

)

SELECT_FORMATS

Set different Options for selecting elements from the FileBrowser

SELECT_FORMATS = getattr(settings FILEBROWSER_SELECT_FORMATS file [FolderImageDocumentVideoAudio]image [Image]document [Document]media [VideoAudio]

)

When using the browse-function for selecting FilesFolders you can use an additional query-attribute type in orderto restrict the choices

124 Versions

VERSIONS_BASEDIR (relative to storage location)

Changed in version 340

Directory to save image versions (and thumbnails) If no directory is given versions are stored at the same location asthe original image

12 Settings 5

Django FileBrowser Documentation Release 357

VERSIONS_BASEDIR = getattr(settings FILEBROWSER_VERSIONS_BASEDIR )

We do recommend the following structure for media files

-- media sitestoragelocation (eg MEDIA_ROOT)-- _versions VERSIONS_BASEDIR (outside of sitedirectory)-- uploads sitedirectory

Warning If VERSIONS_BASEDIR is within sitedirectory it will be browsed

Warning With the next major release (360) the default setting will be ldquo_versionsrdquo

VERSIONS

Define the versions according to your websites grid

VERSIONS = getattr(settings FILEBROWSER_VERSIONS admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

)

VERSION_QUALITY

Quality of saved versions

VERSION_QUALITY = getattr(settings FILEBROWSER_VERSION_QUALITY 90)

ADMIN_VERSIONS

The versions you want to show with the admin interface

ADMIN_VERSIONS = getattr(settings FILEBROWSER_ADMIN_VERSIONS [thumbnail small medium big large])

ADMIN_THUMBNAIL

The version being used as the admin thumbnail

ADMIN_THUMBNAIL = getattr(settings FILEBROWSER_ADMIN_THUMBNAIL admin_thumbnail)

125 Placeholder

With your locale environment you donrsquot necessarily have access to all media files (eg images uploaded by yourclient) Therefore you can use a PLACEHOLDER

6 Chapter 1 Installation and Setup

Django FileBrowser Documentation Release 357

PLACEHOLDER

Path to placeholder image (relative to storage location)

PLACEHOLDER = getattr(settings FILEBROWSER_PLACEHOLDER )

SHOW_PLACEHOLDER

Show placeholder (instead of a version) if the original image does not exist

SHOW_PLACEHOLDER = getattr(settings FILEBROWSER_SHOW_PLACEHOLDER False)

FORCE_PLACEHOLDER

Always show placeholder (even if the original image exists)

FORCE_PLACEHOLDER = getattr(settings FILEBROWSER_FORCE_PLACEHOLDER False)

126 Extra Settings

SAVE_FULL_URL

Deprecated since version 340 With custom storage engines saving the full URL doesnrsquot make sense anymoreMoreover removing this settings allows for easily replacing a FileBrowseField with Djangos File- or ImageField

STRICT_PIL

If set to True the FileBrowser will not try to import a mis-installed PIL

STRICT_PIL = getattr(settings FILEBROWSER_STRICT_PIL False)

IMAGE_MAXBLOCK

see httpmailpythonorgpipermailimage-sig1999-August000816html

IMAGE_MAXBLOCK = getattr(settings FILEBROWSER_IMAGE_MAXBLOCK 10241024)

EXCLUDE

Exclude-patterns for files you donrsquot want to show

EXTENSION_LIST = []for exts in EXTENSIONSvalues()

EXTENSION_LIST += extsEXCLUDE = getattr(settings FILEBROWSER_EXCLUDE (r_((exts)s)__qd13((exts)s) exts (|join(EXTENSION_LIST))))

12 Settings 7

Django FileBrowser Documentation Release 357

MAX_UPLOAD_SIZE

Max Upload Size in Bytes

MAX_UPLOAD_SIZE = getattr(settings FILEBROWSER_MAX_UPLOAD_SIZE 10485760)

NORMALIZE_FILENAME

True if you want to normalize filename on upload and remove all non-alphanumeric characters (except for under-scores spaces amp dashes)

NORMALIZE_FILENAME = getattr(settings FILEBROWSER_NORMALIZE_FILENAME False)

CONVERT_FILENAME

True if you want to convert the filename on upload (replace spaces and convert to lowercase)

CONVERT_FILENAME = getattr(settings FILEBROWSER_CONVERT_FILENAME True)

LIST_PER_PAGE

How many items appear on each paginated list

LIST_PER_PAGE = getattr(settings FILEBROWSER_LIST_PER_PAGE 50)

DEFAULT_SORTING_BY

Default sorting attribute

DEFAULT_SORTING_BY = getattr(settings FILEBROWSER_DEFAULT_SORTING_BY date)

Options are date filesize filename_lower filetype_checked

DEFAULT_SORTING_ORDER

Default sorting order

DEFAULT_SORTING_ORDER = getattr(settings FILEBROWSER_DEFAULT_SORTING_ORDER desc)

Options are asc or desc

FOLDER_REGEX

regex to clean directory names before creation

FOLDER_REGEX = getattr(settings FILEBROWSER_FOLDER_REGEX r^[w_ -]+$)

8 Chapter 1 Installation and Setup

Django FileBrowser Documentation Release 357

SEARCH_TRAVERSE

True if you want to traverse all subdirectories when searching Please note that with thousands of filesdirectoriesthis might take a while

SEARCH_TRAVERSE = getattr(settings FILEBROWSER_SEARCH_TRAVERSE False)

DEFAULT_PERMISSIONS

Default upload and version permissions

DEFAULT_PERMISSIONS = getattr(settings FILEBROWSER_DEFAULT_PERMISSIONS 0755)

OVERWRITE_EXISTING

New in version 351

True in order to overwrite existing files False to use the behaviour of the storage engine

OVERWRITE_EXISTING = getattr(settings FILEBROWSER_OVERWRITE_EXISTING True)

12 Settings 9

Django FileBrowser Documentation Release 357

10 Chapter 1 Installation and Setup

CHAPTER 2

API

21 API

211 FileListing

class FileListing(path filter_func=None sorting_by=None sorting_order=None)Returns a list of FileObjects for a server path see FileObject

Parameters

bull path ndash Relative path to a location within sitestoragelocation

bull filter_func ndash Filter function see example below

bull sorting_by ndash Sort the files by any attribute of FileObject

bull sorting_order ndash Sorting order either ldquoascrdquo or ldquodescrdquo

If you want to list all files within a storage location you do

from filebrowsersites import sitefrom filebrowserbase import FileListingfilelisting = FileListing(sitestoragelocation sorting_by=date sorting_order=desc)

Use a custom filter function to limit the list of files

def filter_filelisting(item) item is a FileObjectreturn itemfiletype = Folder

filelisting = FileListing(sitestoragelocation filter_func=filter_listing sorting_by=date sorting_order=desc)

Methods

For the below examples wersquore using this folder-structure

mediauploadstestfoldertestimagejpgmediauploadsblog1imagesblogimagejpg

Note We defined filter_browse as filter_func (see sitespy) And we did not define aVERSIONS_BASEDIR for this demonstration though it is highly recommended to use one

11

Django FileBrowser Documentation Release 357

listing()Returns all items for the given path with oslistdir(path)

gtgtgt for item in filelistinglisting() print itemblogtestfolder

walk()Returns all items for the given path with oswalk(path)

gtgtgt for item in filelistingwalk() print itemblogblog1blog1imagesblog1imagesblogimagejpgblog1imagesblogimage_admin_thumbnailjpgblog1imagesblogimage_mediumjpgblog1imagesblogimage_smalljpgblog1imagesblogimage_thumbnailjpgtestfoldertestfoldertestimagejpg

files_listing_total()Returns a sorted list of FileObjects for listing()

gtgtgt for item in filelistingfiles_listing_total() print itemuploadsbloguploadstestfolder

files_walk_total()Returns a sorted list of FileObjects for walk()

gtgtgt for item in filelistingfiles_walk_total() print itemuploadsbloguploadsblog1uploadsblog1imagesuploadsblog1imagesblogimagejpguploadsblog1imagesblogimage_admin_thumbnailjpguploadsblog1imagesblogimage_mediumjpguploadsblog1imagesblogimage_smalljpguploadsblog1imagesblogimage_thumbnailjpguploadstestfolderuploadstestfoldertestimagejpg

files_listing_filtered()Returns a sorted and filtered list of FileObjects for listing()

gtgtgt for item in filelistingfiles_listing_filtered() print itemuploadsbloguploadstestfolder

files_walk_filtered()Returns a sorted and filtered list of FileObjects for walk()

12 Chapter 2 API

Django FileBrowser Documentation Release 357

gtgtgt for item in filelistingfiles_walk_filtered() print itemuploadsbloguploadsblog1uploadsblog1imagesuploadsblog1imagesblogimagejpguploadstestfolderuploadstestfoldertestimagejpg

Note The versions are not listed (compared with files_walk_total) because of filter_func

results_listing_total()Number of total files based on files_listing_total()

gtgtgt filelistingresults_listing_total()2

results_walk_total()Number of total files based on files_walk_total()

gtgtgt filelistingresults_walk_total()10

results_listing_filtered()Number of filtered files based on files_listing_filtered()

gtgtgt filelistingresults_listing_filtered()2

results_walk_filtered()Number of filtered files based on files_walk_filtered()

gtgtgt filelistingresults_walk_filtered()6

212 FileObject

class FileObject(path site=None)An object representing a media file

Parameters

bull path ndash Relative path to a location within sitestoragelocation

bull site ndash An optional FileBrowser Site

For example

from filebrowsersites import sitefrom filebrowserbase import FileObjectfileobject = FileObject(ospathjoin(sitedirectorytestfoldertestimagejpg))version = FileObject(ospathjoin(fileobjectversions_basedir testfolder testimage_mediumjpg))

21 API 13

Django FileBrowser Documentation Release 357

Attributes

Initial Attributes

pathPath relative to a storage location (including sitedirectory)

gtgtgt fileobjectpathuploadstestfoldertestimagejpg

headThe directory name of pathname path

gtgtgt fileobjectheaduploadstestfolder

filenameName of the file (including the extension) or name of the folder

gtgtgt fileobjectfilenametestimagejpg

filename_lowerLower type of filename

filename_rootFilename without extension

gtgtgt fileobjectfilename_roottestimage

extensionFile extension including the dot With a folder the extensions is None

gtgtgt fileobjectextensionjpg

mimetypeMimetype based on httpdocspythonorglibrarymimetypeshtml

gtgtgt fileobjectmimetype(imagejpeg None)

General Attributes

filetypeType of the file as defined with EXTENSIONS

gtgtgt fileobjectfiletypeImage

filesizeFilesize in Bytes

gtgtgt fileobjectfilesize870037L

14 Chapter 2 API

Django FileBrowser Documentation Release 357

dateDate based on timemktime

gtgtgt fileobjectdate12997603470

datetimeDatetime object

gtgtgt fileobjectdatetimedatetimedatetime(2011 3 10 13 32 27)

existsTrue if the path exists False otherwise

gtgtgt fileobjectexistsTrue

Path and URL attributes

pathPath relative to a storage location (including sitedirectory)

gtgtgt fileobjectpathuploadstestfoldertestimagejpg

path_relative_directoryPath relative to sitedirectory

gtgtgt fileobjectpath_relative_directorytestfoldertestimagejpg

path_fullAbsolute server path (based on storagepath)

gtgtgt fileobjectpath_fullabsolutepathtoserverlocationtestfoldertestimagejpg

dirnameNew in version 34

The directory (not including sitedirectory)

gtgtgt fileobjectdirnametestfolder

urlURL for the filefolder (based on storageurl)

gtgtgt fileobjecturlmediauploadstestfoldertestimagejpg

Image attributes

The image attributes are only useful if the FileObject represents an image

dimensionsImage dimensions as a tuple

21 API 15

Django FileBrowser Documentation Release 357

gtgtgt fileobjectdimensions(1000 750)

widthImage width in px

gtgtgt fileobjectwidth1000

heightImage height in px

gtgtgt fileobjectheight750

aspectratioAspect ratio (float format)

gtgtgt fileobjectaspectratio133534908

orientationImage orientation either Landscape or Portrait

gtgtgt fileobjectorientationLandscape

Folder attributes

The folder attributes make sense when the FileObject represents a directory (not a file)

directory

Deprecated since version 353 Use path_relative_directory instead

folder

Deprecated since version 353 Use dirname instead

is_folderTrue if path is a folder

gtgtgt fileobjectis_folderFalse

is_emptyTrue if the folder is empty False if the folder is not empty or the FileObject is not a folder

gtgtgt fileobjectis_emptyFalse

Version attributes

is_versiontrue if the File is a version of another File

16 Chapter 2 API

Django FileBrowser Documentation Release 357

gtgtgt fileobjectis_versionFalsegtgtgt versionis_versionTrue

versions_basedirThe relative path (from storage location) to the main versions folder Either VERSIONS_BASEDIR orsitedirectory

gtgtgt fileobjectversions_basedir_versionsgtgtgt versionversions_basedir_versions

originalReturns the original FileObject

gtgtgt fileobjectoriginalltFileObject uploadstestfoldertestimagejpggtgtgtgt versionoriginalltFileObject uploadstestfoldertestimagejpggt

original_filenameGet the filename of an original image from a version

gtgtgt fileobjectoriginal_filenametestimagejpggtgtgt versionoriginal_filenametestimagejpg

Methods

Version methods

versions()List all filenames based on VERSIONS

gtgtgt fileobjectversions()[_versionstestfoldertestimage_admin_thumbnailjpg_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionversions()[]

Note The versions are not being generated

admin_versions()List all filenames based on ADMIN_VERSIONS

gtgtgt fileobjectadmin_versions()[_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg

21 API 17

Django FileBrowser Documentation Release 357

_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionadmin_versions()[]

Note The versions are not being generated

version_name(version_suffix)Get the filename for a version

gtgtgt fileobjectversion_name(medium)testimage_mediumjpg

Note The version is not being generated

version_path(version_suffix)Get the path for a version

gtgtgt fileobjectversion_path(medium)_versionstestfoldertestimage_mediumjpg

Note The version is not being generated

version_generate(version_suffix)Generate a version

gtgtgt fileobjectversion_generate(medium)ltFileObject uploadstestfoldertestimage_mediumjpggt

Please note that a version is only generated if it does not already exist or if the original image is newer than theexisting version

Delete methods

delete()Delete the File or Folder from the server

Warning If you delete a Folder all items within the folder are being deleted

delete_versions()Delete all VERSIONS

delete_admin_versions()Delete all ADMIN_VERSIONS

18 Chapter 2 API

CHAPTER 3

Fields amp Widgets

31 Fields amp Widgets

The FileBrowseField is a custom model field which returns a FileObject The widgets FileInput and ClearableFileIn-put are used with the admin app in order to show an additional thumbnail for images

311 FileBrowseField

class FileBrowseField(max_length[ site directory extensions format options])A subclass of CharField referencing a media file within Returns a FileObject

Parameters

bull site ndash A FileBrowser site (defaults to the main site) see FileBrowser Site

bull directory ndash Directory to browse when clicking the search icon

bull extensions ndash List of allowed extensions see Extensions and Formats

bull format ndash A key from SELECT_FORMATS in order to restrict the selection to specificfiletypes see Extensions and Formats

For example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 directory=images extensions=[jpg] blank=True null=True)document = FileBrowseField(PDF max_length=200 directory=documents extensions=[pdfdoc] blank=True null=True)

FileBrowseField in Templates

You can use all attributes from FileObject

blogentryimage ltimg src= publicationimageurl gt

ifequal blogentryimageimage_orientation landscape ltimg src= blogentryimageurl class=landscape gt

endifequal

19

Django FileBrowser Documentation Release 357

Showing Thumbnail in the Changelist

To show a thumbnail with the changelist you can define a ModelAdmin method

from filebrowsersettings import ADMIN_THUMBNAIL

def image_thumbnail(self obj)if objimage and objimagefiletype == Image

return ltimg src=s gt objimageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Using the FileBrowseField with TinyMCE

In order to replace the TinyMCE imagefile manager with the FileBrowser you have to use a FileBrowser CallbackTherersquos an example TinyMCE configuration file in staticjs called TinyMCEAdminjs You can either copy theFileBrowserCallback to your own file or just use tinymce_setupjs (which comes with django-grappelli)

Just add these lines to your ModelAdmin asset definitions

class Mediajs = [pathtotinymcejscriptstiny_mcetiny_mcejs

pathtoyourtinymce_setupjs]

312 FileInput

Subclass of FileInput with an additional thumbnail

from filebrowserwidgets import FileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget FileInput

313 ClearableFileInput

Subclass of ClearableFileInput with an additional thumbnail

from filebrowserwidgets import ClearableFileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget ClearableFileInput

314 Django FileField and the FileBrowser

Return a FileObject from a FileField or ImageField with

20 Chapter 3 Fields amp Widgets

Django FileBrowser Documentation Release 357

from filebrowserbase import FileObject

image_upload = modelsImageField(uImage (Upload) max_length=250 upload_to=image_upload_path blank=True null=True)

def image(self)if selfimage_upload

return FileObject(selfimage_uploadpath)return None

In order show a thumbnail with your changelist you could use a ModelAdmin method

from filebrowserbase import FileObject

def image_thumbnail(self obj)if objimage_upload

image = FileObject(objimage_uploadpath)if imagefiletype == Image

return ltimg src=s gt imageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Note There are different ways to achieve this The above examples show one of several options

31 Fields amp Widgets 21

Django FileBrowser Documentation Release 357

22 Chapter 3 Fields amp Widgets

CHAPTER 4

Admin Interface

41 Admin Interface

The main FileBrowser admin application is an extension for the Django admin interface in order to browser yourmedia folder upload and renamedelete files

411 FileBrowser Site

New in version 340

class FileBrowserSite(name=None app_name=rsquofilebrowserrsquo storage=default_storage)Respresents the FileBrowser admin application (similar to Djangorsquos admin site)

Parameters

bull name ndash A name for the site defaults to None

bull app_name ndash Defaults to lsquofilebrowserrsquo

bull storage ndash A custom storage engine defaults to Djangos default storage

Similar to djangocontribadmin you first need to add a filebrowsersite to your admin interface Inyour urlspy import the default FileBrowser site (or your custom site) and add the site to your URL-patterns (beforeany admin-urls)

from filebrowsersites import site

urlpatterns = patterns(url(r^adminurlfilebrowser include(siteurls))

)

Now you are able to browse the location defined with the storage engine associated to your site

from djangocorefilesstorage import DefaultStoragefrom filebrowsersites import FileBrowserSite

Default FileBrowser sitesite = FileBrowserSite(name=filebrowser storage=DefaultStorage())

My Custom FileBrowser sitecustom_site = FileBrowserSite(name=custom_filebrowser storage=DefaultStorage())custom_sitedirectory = custom_uploads

23

Django FileBrowser Documentation Release 357

Note The module variable site from filebrowsersites is the default FileBrowser application

412 Custom Actions

New in version 340

Similar to Djangorsquos admin actions you can define your FileBrowser actions and thus automate the typical tasks ofyour users Registered custom actions are listed in the detail view of a file and a user can select a single action at atime The selected action will then be applied to the file

The default FileBrowser image actions such as ldquoFlip Verticalrdquo or ldquoRotate 90deg Clockwiserdquo are in fact implemented ascustom actions (see the module filebrowseractions)

Writing Your Own Actions

Custom actions are simple functions

def foo(request fileobjects) Do something with the fileobjects

The first parameter is a HttpRequest object (representing the submitted form in which a user selected the action)and the second parameter is a list of FileObjects to which the action should be applied

The list contains exactly one instance of FileObject (representing the file from the detail view) but this may change inthe future as custom actions may become available also in browse views (similar to admin actions applied to a list ofchecked objects)

Registering an Action

In order to make your action visible you need to register it with a FileBrowser site

siteadd_action(foo)

Once registered the action will appear in the detail view of a file You can also give your action a short description

fooshort_description = Do foo with the File

This short description will then appear in the list of available actions If you do not provide a short description thefunction name will be used instead and FileBrowser will replace any underscores in the function name with spaces

Associating Actions with Specific Files

Each custom action can be associated with a specific file type (eg images audio file etc) to which it applies In orderto do that you need to define a predicatefilter function which takes a single argument (FileObject) and returns Trueif your action is applicable to that FileObject Finally you need to register this filter function with your action

fooapplies_to(lambda fileobject fileobjectfiletype == Image)

In the above example foo will appear in the action list only for image files If you do not specify any filter functionfor your action FileBrowser considers the action as applicable to all files

24 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

Messages amp Intermediate Pages

You can provide a feedback to a user about a successful or failed execution of an action by using a message Forexample

from djangocontrib import messages

def desaturate_image(request fileobjects)for f in fileobjects

Desaturate the imagemessagesadd_message(request messagesSUCCESS _(Image s was desaturated) ffilename)

Some actions may require user confirmation (eg in order to prevent accidental and irreversible modification tofiles) In order to that follow the same pattern as with Djangorsquos admin action and return a HttpResponse objectfrom your action Good practice for intermediate pages is to implement a confirm view and have your action returnHttpResponseRedirect

def crop_image(request fileobjects)files = ampf=join([fpath_relative for f in fileobjects])return HttpResponseRedirect(confirmaction=crop_imageampf=s files)

413 File Storages

New in version 340

You have the option to specify which file storage engine a FileBrowser should use to browseuploadmodify yourmedia files This enables you to use a FileBrowser even if your media files are located at some remote system Seealso the Djangorsquos documentation on storages httpsdocsdjangoprojectcomendevtopicsfiles

To associate a FileBrowser site with a particular storage engine set the storage property of a site object

from djangocorefilesstorage import FileSystemStoragesitestorage = FileSystemStorage(location=pathtomediadirectory base_url=media)

For storage classes other than FileSystemStorage (or those that inherit from that class) therersquos more effort involved inproviding a storage object that can be used with FileBrowser See StorageMixin Class

Note Prior FileBrowser 34 the way to specify FileBrowserlsquos MEDIA_ROOT and MEDIA_URL was via settingspyStarting from version 34 those variables are associated with the storage instance and you can set them as illustratedin the above example

Warning For the reason of backward compatibility FileBrowser settings FILEBROWSER_MEDIA_ROOT andFILEBROWSER_MEDIA_URL can still be used to customize FileBrowser as long as yoursquore using the defaultFileBrowserlsquos site without having changed its storage engine In the next major release of FileBrowser thesesettings will be removed

StorageMixin Class

A FileBrowser uses the Djangorsquos Storage class to access media files However the API of the Storageclass does not provide all methods necessary for FileBrowserrsquos functionality A StorageMixin class fromfilebrowserstorage module therefore defines all the additional methods that a FileBrowser requires

isdir(self name)Returns true if name exists and is a directory

41 Admin Interface 25

Django FileBrowser Documentation Release 357

isfile(self name)Returns true if name exists and is a regular file

move(self old_file_name new_file_name allow_overwrite=False)Moves safely a file from one location to another If allow_ovewrite==False and new_file_nameexists raises an exception

makedirs(self name)Creates all missing directories specified by name Analogue to osmkdirs()

414 Views

All views use the staff_member_requird and path_exists decorator in order to check if the server pathactually exists Some views also use the file_exists decorator

bull Browse fb_browse Browse a directory on your server Returns a FileListing

ndash Optional query string args dir o ot q p filter_date filter_type type

bull Create directory fb_createdir Create a new folder on your server

ndash Optional query string args dir

ndash Signals filebrowser_pre_createdir filebrowser_post_createdir

bull Upload fb_upload Multiple upload

ndash Optional query string args dir type

ndash Signals filebrowser_pre_upload filebrowser_post_upload

bull Edit fb_edit Edit a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_rename filebrowser_post_rename

You are able to apply custom actions (see Custom Actions) to the edit-view

bull Confirm delete fb_confirm_delete Confirm the deletion of a file or folder

ndash Required query string args filename

ndash Optional query string args dir

If you try to delete a folder all filesfolders within this folder are listed on this page

bull Delete fb_delete Delete a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_delete filebrowser_post_delete

Warning If you delete a Folder all items within this Folder are being deleted

bull Version fb_version Generate a version of an image as defined with ADMIN_VERSIONS

ndash Required query string args filename

ndash Optional Query string args dir

This is a helper used by the FileBrowseField and TinyMCE for selecting a version

26 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

415 Signals

The FileBrowser sends a couple of different signals Please take a look at the module filebrowsersignals for furtherexplanation on the provided arguments

bull filebrowser_pre_upload Sent before a an Upload starts

bull filebrowser_post_upload Sent after an Upload has finished

bull filebrowser_pre_delete Sent before an Item (File Folder) is deleted

bull filebrowser_post_delete Sent after an Item (File Folder) has been deleted

bull filebrowser_pre_createdir Sent before a new Folder is created

bull filebrowser_post_createdir Sent after a new Folder has been created

bull filebrowser_pre_rename Sent before an Item (File Folder) is renamed

bull filebrowser_post_rename Sent after an Item (File Folder) has been renamed

bull filebrowser_actions_pre_apply Sent before a custom action is applied

bull filebrowser_actions_post_apply Sent after a custom action has been applied

Example for using these Signals

Herersquos a small example for using the above Signals

from filebrowser import signals

def pre_upload_callback(sender kwargs)Receiver function called before an upload startsprint Pre Upload Callbackprint kwargs kwargs

signalsfilebrowser_pre_uploadconnect(pre_upload_callback)

def post_upload_callback(sender kwargs)Receiver function called each time an upload has finishedprint Post Upload Callbackprint kwargs kwargs You can use all attributes available with the FileObject This is just an example print Filesize kwargs[file]filesizeprint Orientation kwargs[file]orientationprint Extension kwargs[file]extension

signalsfilebrowser_post_uploadconnect(post_upload_callback)

41 Admin Interface 27

Django FileBrowser Documentation Release 357

28 Chapter 4 Admin Interface

CHAPTER 5

Image Versions

51 Versions

With the FileBrowser you are able to define different versionssizes for images This enables you to save an originalimage on your server while having different versions of that image to automatically fit your websites grid Versionsare also useful for responsiveadaptive layouts

511 Defining Versions

New in version 340 methods

First you need to know which versionssizes of an image yoursquod like to generate with your website Letrsquos say yoursquoreusing a 12 column grid with 60px for each column and 20px margin (which is a total of 940px) With this grid youcould (for example) define these image versions

FILEBROWSER_VERSIONS_BASEDIR = _versionsFILEBROWSER_VERSIONS =

admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

Use the methods argument if you need to add a filter

def grayscale(im)Convert image to grayscaleif immode = L

im = imconvert(L)return im

FILEBROWSER_VERSIONS = big verbose_name Big (6 col) width 460 height opts methods [grayscale]

)

29

Django FileBrowser Documentation Release 357

512 Versions and the Admin

When using the FileBrowser with the admin interface you need to define ADMIN_VERSIONS andADMIN_THUMBNAIL (see Settings) ADMIN_VERSIONS are available with the admin ie you are able to seethese versions with the image detail view and you are able to select the versions with the FileBrowseField model field

FILEBROWSER_ADMIN_VERSIONS = [thumbnail small medium big large]FILEBROWSER_ADMIN_THUMBNAIL = admin_thumbnail

513 Versions and the Frontend

With your templates you have two different tags to choose from version and version_object With bothtags the version will be generated if it doesnrsquot already exist OR if the original image is newer than the version Inorder to update an image you just overwrite the original image and the versions will be generated automatically (asyou request them within your template)

A Model example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 blank=True null=True)

With your templates use version if you simply need to retrieve the URL or version_object if you need to geta FileObject

lt-- load filebrowser templatetags --gt load fb_versions

lt-- get the url with version --gtltimg src= version blogentryimage medium gt

lt-- get a fileobject with version_object --gt version_object blogentryimage medium as version_medium version_mediumwidth ltimg src= version_medium gt

Templatetag version

RetrievesGenerates a version and returns an URL

version modelfield_name version_prefix

Templatetag version_object

RetrievesGenerates a version and returns a FileObject

version_object modelfield_name version_prefix as variable

Note With both templatetags version_prefix can either be a string or a variable If version_prefix is astring use quotes

30 Chapter 5 Image Versions

Django FileBrowser Documentation Release 357

514 Versions in Views

If you have a FileObject you can generateretrieve a version with

v = objimageversion_generate(version_prefix) returns a FileObject

515 Placeholder

When developing on a locale machine or a development-server you might not have all the images (resp media-files)available that are on your production instance and downloading these files on a regular basis might not be an option

In that case you can use a placeholder instead of a version You just need to define the PLACEHOLDER and overwritethe settings SHOW_PLACEHOLDER andor FORCE_PLACEHOLDER (see Placeholder)

516 Management Commands

fb_version_generateIf you need to generate certain (or all) versions type

python managepy fb_version_generate

fb_version_removeIf you need to generate certain (or all) versions type

python managepy fb_version_generate

Warning Please be very careful with this command

51 Versions 31

Django FileBrowser Documentation Release 357

32 Chapter 5 Image Versions

CHAPTER 6

Help

61 Help

611 FAQ

Why should I use the FileBrowser

If you need your editors or customers to manage files the FileBrowser is an alternative to an FTP-client Moreoveryou are able to define different image versions according to your websites grid Alternatives to the FileBrowser can befound at httpdjangopackagescomgridsgfile-managers

Do I need Grappelli

Grappelli is a requirement for using the FileBrowser There are several filebrowser-no-grappelli repositories (most ofthem on GitHub) but we donrsquot follow the development

I need help

see Troubleshooting

Why are there no fancy effects

The FileBrowser is about managing files We think that you should prepare your files before uploading them to theserver

How do I upload to another server

Use a custom storage engine see httpsdocsdjangoprojectcomen16howtocustom-file-storage

Why do I need image-versions

You need image-versions if your website is based on a grid

33

Django FileBrowser Documentation Release 357

Is the FileBrowser stable

Wersquove developed the FileBrowser for a couple of years and use it with almost all of our clients That said Grappelli isthe more stable and mature application

How can I contribute

Help is very much needed and appreciated Test the FileBrowser and submit feedbackpatches

Who develops the FileBrowser

The FileBrowser is developed and maintained by Patrick Kranzlmuumlller amp Axel Swoboda of vonautomatisch

612 Troubleshooting

Check your setup

Please check if the problem is caused by your setup

bull Read Quick start guide

bull Check if the staticmedia-files are served correctly

bull Make sure you have removed all custom FileBrowser templates from all locations in TEMPLATE_DIRS orcheck that these templates are compatible with the FileBrowser

Run the tests

Start the shell and type

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Check issues

If your setup is fine please check if your problem is a known issue

bull Take a look at all FileBrowser Issues (incuding closed) and search the FileBrowser Google-Group

Add a ticket

If you think yoursquove found a bug please add a ticket

bull Try to describe your problem as precisely as possible

bull Tell us what you did in order to solve the problem

bull Tell us what version of the FileBrowser you are using

bull Tell us what version of Django you are using

34 Chapter 6 Help

Django FileBrowser Documentation Release 357

bull Please do NOT add tickets if yoursquore having problems with serving staticmedia-files (because this is not relatedto the FileBrowser)

bull Please do NOT add tickets referring to Djangos trunk version

bull At best add a patch

Note Be aware that we may close issues not following these guidlines without further notifications

613 Translation

Translation is done via Transifex

Supported Languages

see httpswwwtransifexnetprojectspdjango-filebrowserresourcedjangopo

614 FileBrowser 35 Release Notes

FileBrowser 35 is compatible with Django 14151617 as well as Grappelli 242526

Update from FileBrowser 34x

bull Update Django to 14151617 and check httpsdocsdjangoprojectcomendevreleases14 orhttpsdocsdjangoprojectcomendevreleases15 or httpsdocsdjangoprojectcomendevreleases16

bull Update Grappelli to 24x25x26x

bull Update FileBrowser to 35x

62 Changelog

621 358 (not yet released)

622 357 (September 10th 2014)

bull New Compatibility with Django 17 and Grappelli 26x

bull Improved Updated tests because of the new random suffix with get_available_name (django storage)

bull Improved Added an icon in order to mark finished uploads

bull Improved Show resulting filename (eg with suffix converted) after successful upload

bull Fixed Permissions with file upload

bull Fixed Unified json response with _upload_file (no matter if file already exists or not)

623 356 (April 16th 2014)

bull Fixed Displaying pagination correctly with lots of entries

62 Changelog 35

Django FileBrowser Documentation Release 357

624 355 (April 13th 2014)

bull New Added client-side (JavaScript) file extension validation to the AJAX uploader

bull New Added experimental Python 33 support

bull Improved Tests with convertnormalize (removed special chars from test filename)

bull Fixed File selection after using search box (CKEditor)

bull Fixed Removed encoding of file URIs with CKEditor

625 354 (February 21st 2014)

bull Fixed Placeholder functionality (including tests)

bull Fixed Convertnormalize filenames (including tests)

bull Fixed Handling uppercase extensions with browse

626 353 (January 7 2014)

bull New added path_full to FileObject

bull Improved added docx to EXTENSIONS

bull Improved Recommend pillow instead of PIL as a requirement

bull Improved Added additional test cases

bull Improved Updated documentation

bull Improved Consistent use of storage (eg storagelocation storageurl)

bull Improved Removed unnecessary functions (eg url_join url_strip)

bull Improved Moved sort_by_attr to FileListing

bull Improved Regex matches with file versions on browse

bull Improved Using djangoconfurls (with djangoconfurlsdefaults as fallback)

bull Improved Adding CONTRIBUTINGrst

bull Improved Removed static Media inner class with fields

bull Improved Removed search icon with fields (has not being used)

bull Improved Added custom class attributes with filebrowser field

bull Improved Updated translations

bull Fixed fixed exception handling with python 25

bull Fixed fixes dir with SEARCH_TRAVERSE true and version select

bull Fixed Make Django FileUploadHandlers work (also fixed a memory leak)

bull Fixed return correct filename with OVERWRITE_EXISTING

bull Fixed fb_version_generate with FILEBROWSER_VERSIONS_BASEDIR

bull Fixed Table sorting with ascdesc

bull Fixed Added DeprecationWarning for FileObjectdirectory and FileObjectfolder

36 Chapter 6 Help

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

Django FileBrowser Documentation Release 357

2 Contents

CHAPTER 1

Installation and Setup

11 Quick start guide

For using the FileBrowser Django needs to be installed and an Admin Site has to be activated

111 Requirements

bull Django 14151617 httpwwwdjangoprojectcom

bull Grappelli 242526 httpsgithubcomsehmaschinedjango-grappelli

bull Pillow httpsgithubcompython-imagingPillow

112 Installation

Install the FileBrowser

pip install django-filebrowser

Add the filebrowser to your INSTALLED_APPS (before djangocontribadmin)

INSTALLED_APPS = (grappellifilebrowserdjangocontribadmin

)

Add the FileBrowser site to your url-patterns (before any admin-urls)

from filebrowsersites import site

urlpatterns = patterns((r^adminfilebrowser include(siteurls))(r^grappelli include(grappelliurls))(r^admin include(adminsiteurls))

)

Collect the static files (please refer to the Staticfiles Documentation for more information)

python managepy collectstatic

3

Django FileBrowser Documentation Release 357

113 Settings

Check the Settings

Note You need to add a folder ldquouploadsrdquo within sitestoragelocation when using the default settingsAnd we strongly recommend to define a VERSIONS_BASEDIR

114 Testing

Run the FileBrowser tests

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Start the devserver and login to your admin site

python managepy runserver ltIP-addressgt8000

Goto adminfilebrowserbrowse and check if everything looksworks as expected If yoursquore having problems seeTroubleshooting

12 Settings

There are some settings in order to customize the FileBrowser Nonetheless you should be able to start with the defaultsettings

All settings can be defined in your projects settings-file In that case you have to use the prefix FILEBROWSER_ forevery setting (eg FILEBROWSER_EXTENSIONS instead of EXTENSIONS)

121 Main URLPaths Settings

MEDIA_ROOT

Warning Will be removed with version 360 Since 34 MEDIA_ROOT is defined with your storage engine

The absolute path to the directory that holds the media-files you want to browse

MEDIA_ROOT = getattr(settings FILEBROWSER_MEDIA_ROOT settingsMEDIA_ROOT)

MEDIA_URL

Warning Will be removed with version 360 Since 34 MEDIA_URL is defined with your storage engine

URL that handles the media served from MEDIA_ROOT

MEDIA_URL = getattr(settings FILEBROWSER_MEDIA_URL settingsMEDIA_URL)

4 Chapter 1 Installation and Setup

Django FileBrowser Documentation Release 357

DIRECTORY (relative to storage location)

Main FileBrowser Directory Leave empty in order to browse all files and folders within a storage location

DIRECTORY = getattr(settings FILEBROWSER_DIRECTORY uploads)

You can override this setting on a perndashsite basis

from filebrowsersites import sitesitedirectory = uploads

122 FileBrowser Media TinyMCE Media

Deprecated since version 353 Use staticfiles instead

123 Extensions and Formats

EXTENSIONS

Allowed extensions for file upload

EXTENSIONS = getattr(settings FILEBROWSER_EXTENSIONS Folder []Image [jpgjpeggifpngtiftiff]Document [pdfdocrtftxtxlscsv]Video [movwmvmpegmpgavirm]Audio [mp3mp4wavaiffmidim4p]

)

SELECT_FORMATS

Set different Options for selecting elements from the FileBrowser

SELECT_FORMATS = getattr(settings FILEBROWSER_SELECT_FORMATS file [FolderImageDocumentVideoAudio]image [Image]document [Document]media [VideoAudio]

)

When using the browse-function for selecting FilesFolders you can use an additional query-attribute type in orderto restrict the choices

124 Versions

VERSIONS_BASEDIR (relative to storage location)

Changed in version 340

Directory to save image versions (and thumbnails) If no directory is given versions are stored at the same location asthe original image

12 Settings 5

Django FileBrowser Documentation Release 357

VERSIONS_BASEDIR = getattr(settings FILEBROWSER_VERSIONS_BASEDIR )

We do recommend the following structure for media files

-- media sitestoragelocation (eg MEDIA_ROOT)-- _versions VERSIONS_BASEDIR (outside of sitedirectory)-- uploads sitedirectory

Warning If VERSIONS_BASEDIR is within sitedirectory it will be browsed

Warning With the next major release (360) the default setting will be ldquo_versionsrdquo

VERSIONS

Define the versions according to your websites grid

VERSIONS = getattr(settings FILEBROWSER_VERSIONS admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

)

VERSION_QUALITY

Quality of saved versions

VERSION_QUALITY = getattr(settings FILEBROWSER_VERSION_QUALITY 90)

ADMIN_VERSIONS

The versions you want to show with the admin interface

ADMIN_VERSIONS = getattr(settings FILEBROWSER_ADMIN_VERSIONS [thumbnail small medium big large])

ADMIN_THUMBNAIL

The version being used as the admin thumbnail

ADMIN_THUMBNAIL = getattr(settings FILEBROWSER_ADMIN_THUMBNAIL admin_thumbnail)

125 Placeholder

With your locale environment you donrsquot necessarily have access to all media files (eg images uploaded by yourclient) Therefore you can use a PLACEHOLDER

6 Chapter 1 Installation and Setup

Django FileBrowser Documentation Release 357

PLACEHOLDER

Path to placeholder image (relative to storage location)

PLACEHOLDER = getattr(settings FILEBROWSER_PLACEHOLDER )

SHOW_PLACEHOLDER

Show placeholder (instead of a version) if the original image does not exist

SHOW_PLACEHOLDER = getattr(settings FILEBROWSER_SHOW_PLACEHOLDER False)

FORCE_PLACEHOLDER

Always show placeholder (even if the original image exists)

FORCE_PLACEHOLDER = getattr(settings FILEBROWSER_FORCE_PLACEHOLDER False)

126 Extra Settings

SAVE_FULL_URL

Deprecated since version 340 With custom storage engines saving the full URL doesnrsquot make sense anymoreMoreover removing this settings allows for easily replacing a FileBrowseField with Djangos File- or ImageField

STRICT_PIL

If set to True the FileBrowser will not try to import a mis-installed PIL

STRICT_PIL = getattr(settings FILEBROWSER_STRICT_PIL False)

IMAGE_MAXBLOCK

see httpmailpythonorgpipermailimage-sig1999-August000816html

IMAGE_MAXBLOCK = getattr(settings FILEBROWSER_IMAGE_MAXBLOCK 10241024)

EXCLUDE

Exclude-patterns for files you donrsquot want to show

EXTENSION_LIST = []for exts in EXTENSIONSvalues()

EXTENSION_LIST += extsEXCLUDE = getattr(settings FILEBROWSER_EXCLUDE (r_((exts)s)__qd13((exts)s) exts (|join(EXTENSION_LIST))))

12 Settings 7

Django FileBrowser Documentation Release 357

MAX_UPLOAD_SIZE

Max Upload Size in Bytes

MAX_UPLOAD_SIZE = getattr(settings FILEBROWSER_MAX_UPLOAD_SIZE 10485760)

NORMALIZE_FILENAME

True if you want to normalize filename on upload and remove all non-alphanumeric characters (except for under-scores spaces amp dashes)

NORMALIZE_FILENAME = getattr(settings FILEBROWSER_NORMALIZE_FILENAME False)

CONVERT_FILENAME

True if you want to convert the filename on upload (replace spaces and convert to lowercase)

CONVERT_FILENAME = getattr(settings FILEBROWSER_CONVERT_FILENAME True)

LIST_PER_PAGE

How many items appear on each paginated list

LIST_PER_PAGE = getattr(settings FILEBROWSER_LIST_PER_PAGE 50)

DEFAULT_SORTING_BY

Default sorting attribute

DEFAULT_SORTING_BY = getattr(settings FILEBROWSER_DEFAULT_SORTING_BY date)

Options are date filesize filename_lower filetype_checked

DEFAULT_SORTING_ORDER

Default sorting order

DEFAULT_SORTING_ORDER = getattr(settings FILEBROWSER_DEFAULT_SORTING_ORDER desc)

Options are asc or desc

FOLDER_REGEX

regex to clean directory names before creation

FOLDER_REGEX = getattr(settings FILEBROWSER_FOLDER_REGEX r^[w_ -]+$)

8 Chapter 1 Installation and Setup

Django FileBrowser Documentation Release 357

SEARCH_TRAVERSE

True if you want to traverse all subdirectories when searching Please note that with thousands of filesdirectoriesthis might take a while

SEARCH_TRAVERSE = getattr(settings FILEBROWSER_SEARCH_TRAVERSE False)

DEFAULT_PERMISSIONS

Default upload and version permissions

DEFAULT_PERMISSIONS = getattr(settings FILEBROWSER_DEFAULT_PERMISSIONS 0755)

OVERWRITE_EXISTING

New in version 351

True in order to overwrite existing files False to use the behaviour of the storage engine

OVERWRITE_EXISTING = getattr(settings FILEBROWSER_OVERWRITE_EXISTING True)

12 Settings 9

Django FileBrowser Documentation Release 357

10 Chapter 1 Installation and Setup

CHAPTER 2

API

21 API

211 FileListing

class FileListing(path filter_func=None sorting_by=None sorting_order=None)Returns a list of FileObjects for a server path see FileObject

Parameters

bull path ndash Relative path to a location within sitestoragelocation

bull filter_func ndash Filter function see example below

bull sorting_by ndash Sort the files by any attribute of FileObject

bull sorting_order ndash Sorting order either ldquoascrdquo or ldquodescrdquo

If you want to list all files within a storage location you do

from filebrowsersites import sitefrom filebrowserbase import FileListingfilelisting = FileListing(sitestoragelocation sorting_by=date sorting_order=desc)

Use a custom filter function to limit the list of files

def filter_filelisting(item) item is a FileObjectreturn itemfiletype = Folder

filelisting = FileListing(sitestoragelocation filter_func=filter_listing sorting_by=date sorting_order=desc)

Methods

For the below examples wersquore using this folder-structure

mediauploadstestfoldertestimagejpgmediauploadsblog1imagesblogimagejpg

Note We defined filter_browse as filter_func (see sitespy) And we did not define aVERSIONS_BASEDIR for this demonstration though it is highly recommended to use one

11

Django FileBrowser Documentation Release 357

listing()Returns all items for the given path with oslistdir(path)

gtgtgt for item in filelistinglisting() print itemblogtestfolder

walk()Returns all items for the given path with oswalk(path)

gtgtgt for item in filelistingwalk() print itemblogblog1blog1imagesblog1imagesblogimagejpgblog1imagesblogimage_admin_thumbnailjpgblog1imagesblogimage_mediumjpgblog1imagesblogimage_smalljpgblog1imagesblogimage_thumbnailjpgtestfoldertestfoldertestimagejpg

files_listing_total()Returns a sorted list of FileObjects for listing()

gtgtgt for item in filelistingfiles_listing_total() print itemuploadsbloguploadstestfolder

files_walk_total()Returns a sorted list of FileObjects for walk()

gtgtgt for item in filelistingfiles_walk_total() print itemuploadsbloguploadsblog1uploadsblog1imagesuploadsblog1imagesblogimagejpguploadsblog1imagesblogimage_admin_thumbnailjpguploadsblog1imagesblogimage_mediumjpguploadsblog1imagesblogimage_smalljpguploadsblog1imagesblogimage_thumbnailjpguploadstestfolderuploadstestfoldertestimagejpg

files_listing_filtered()Returns a sorted and filtered list of FileObjects for listing()

gtgtgt for item in filelistingfiles_listing_filtered() print itemuploadsbloguploadstestfolder

files_walk_filtered()Returns a sorted and filtered list of FileObjects for walk()

12 Chapter 2 API

Django FileBrowser Documentation Release 357

gtgtgt for item in filelistingfiles_walk_filtered() print itemuploadsbloguploadsblog1uploadsblog1imagesuploadsblog1imagesblogimagejpguploadstestfolderuploadstestfoldertestimagejpg

Note The versions are not listed (compared with files_walk_total) because of filter_func

results_listing_total()Number of total files based on files_listing_total()

gtgtgt filelistingresults_listing_total()2

results_walk_total()Number of total files based on files_walk_total()

gtgtgt filelistingresults_walk_total()10

results_listing_filtered()Number of filtered files based on files_listing_filtered()

gtgtgt filelistingresults_listing_filtered()2

results_walk_filtered()Number of filtered files based on files_walk_filtered()

gtgtgt filelistingresults_walk_filtered()6

212 FileObject

class FileObject(path site=None)An object representing a media file

Parameters

bull path ndash Relative path to a location within sitestoragelocation

bull site ndash An optional FileBrowser Site

For example

from filebrowsersites import sitefrom filebrowserbase import FileObjectfileobject = FileObject(ospathjoin(sitedirectorytestfoldertestimagejpg))version = FileObject(ospathjoin(fileobjectversions_basedir testfolder testimage_mediumjpg))

21 API 13

Django FileBrowser Documentation Release 357

Attributes

Initial Attributes

pathPath relative to a storage location (including sitedirectory)

gtgtgt fileobjectpathuploadstestfoldertestimagejpg

headThe directory name of pathname path

gtgtgt fileobjectheaduploadstestfolder

filenameName of the file (including the extension) or name of the folder

gtgtgt fileobjectfilenametestimagejpg

filename_lowerLower type of filename

filename_rootFilename without extension

gtgtgt fileobjectfilename_roottestimage

extensionFile extension including the dot With a folder the extensions is None

gtgtgt fileobjectextensionjpg

mimetypeMimetype based on httpdocspythonorglibrarymimetypeshtml

gtgtgt fileobjectmimetype(imagejpeg None)

General Attributes

filetypeType of the file as defined with EXTENSIONS

gtgtgt fileobjectfiletypeImage

filesizeFilesize in Bytes

gtgtgt fileobjectfilesize870037L

14 Chapter 2 API

Django FileBrowser Documentation Release 357

dateDate based on timemktime

gtgtgt fileobjectdate12997603470

datetimeDatetime object

gtgtgt fileobjectdatetimedatetimedatetime(2011 3 10 13 32 27)

existsTrue if the path exists False otherwise

gtgtgt fileobjectexistsTrue

Path and URL attributes

pathPath relative to a storage location (including sitedirectory)

gtgtgt fileobjectpathuploadstestfoldertestimagejpg

path_relative_directoryPath relative to sitedirectory

gtgtgt fileobjectpath_relative_directorytestfoldertestimagejpg

path_fullAbsolute server path (based on storagepath)

gtgtgt fileobjectpath_fullabsolutepathtoserverlocationtestfoldertestimagejpg

dirnameNew in version 34

The directory (not including sitedirectory)

gtgtgt fileobjectdirnametestfolder

urlURL for the filefolder (based on storageurl)

gtgtgt fileobjecturlmediauploadstestfoldertestimagejpg

Image attributes

The image attributes are only useful if the FileObject represents an image

dimensionsImage dimensions as a tuple

21 API 15

Django FileBrowser Documentation Release 357

gtgtgt fileobjectdimensions(1000 750)

widthImage width in px

gtgtgt fileobjectwidth1000

heightImage height in px

gtgtgt fileobjectheight750

aspectratioAspect ratio (float format)

gtgtgt fileobjectaspectratio133534908

orientationImage orientation either Landscape or Portrait

gtgtgt fileobjectorientationLandscape

Folder attributes

The folder attributes make sense when the FileObject represents a directory (not a file)

directory

Deprecated since version 353 Use path_relative_directory instead

folder

Deprecated since version 353 Use dirname instead

is_folderTrue if path is a folder

gtgtgt fileobjectis_folderFalse

is_emptyTrue if the folder is empty False if the folder is not empty or the FileObject is not a folder

gtgtgt fileobjectis_emptyFalse

Version attributes

is_versiontrue if the File is a version of another File

16 Chapter 2 API

Django FileBrowser Documentation Release 357

gtgtgt fileobjectis_versionFalsegtgtgt versionis_versionTrue

versions_basedirThe relative path (from storage location) to the main versions folder Either VERSIONS_BASEDIR orsitedirectory

gtgtgt fileobjectversions_basedir_versionsgtgtgt versionversions_basedir_versions

originalReturns the original FileObject

gtgtgt fileobjectoriginalltFileObject uploadstestfoldertestimagejpggtgtgtgt versionoriginalltFileObject uploadstestfoldertestimagejpggt

original_filenameGet the filename of an original image from a version

gtgtgt fileobjectoriginal_filenametestimagejpggtgtgt versionoriginal_filenametestimagejpg

Methods

Version methods

versions()List all filenames based on VERSIONS

gtgtgt fileobjectversions()[_versionstestfoldertestimage_admin_thumbnailjpg_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionversions()[]

Note The versions are not being generated

admin_versions()List all filenames based on ADMIN_VERSIONS

gtgtgt fileobjectadmin_versions()[_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg

21 API 17

Django FileBrowser Documentation Release 357

_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionadmin_versions()[]

Note The versions are not being generated

version_name(version_suffix)Get the filename for a version

gtgtgt fileobjectversion_name(medium)testimage_mediumjpg

Note The version is not being generated

version_path(version_suffix)Get the path for a version

gtgtgt fileobjectversion_path(medium)_versionstestfoldertestimage_mediumjpg

Note The version is not being generated

version_generate(version_suffix)Generate a version

gtgtgt fileobjectversion_generate(medium)ltFileObject uploadstestfoldertestimage_mediumjpggt

Please note that a version is only generated if it does not already exist or if the original image is newer than theexisting version

Delete methods

delete()Delete the File or Folder from the server

Warning If you delete a Folder all items within the folder are being deleted

delete_versions()Delete all VERSIONS

delete_admin_versions()Delete all ADMIN_VERSIONS

18 Chapter 2 API

CHAPTER 3

Fields amp Widgets

31 Fields amp Widgets

The FileBrowseField is a custom model field which returns a FileObject The widgets FileInput and ClearableFileIn-put are used with the admin app in order to show an additional thumbnail for images

311 FileBrowseField

class FileBrowseField(max_length[ site directory extensions format options])A subclass of CharField referencing a media file within Returns a FileObject

Parameters

bull site ndash A FileBrowser site (defaults to the main site) see FileBrowser Site

bull directory ndash Directory to browse when clicking the search icon

bull extensions ndash List of allowed extensions see Extensions and Formats

bull format ndash A key from SELECT_FORMATS in order to restrict the selection to specificfiletypes see Extensions and Formats

For example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 directory=images extensions=[jpg] blank=True null=True)document = FileBrowseField(PDF max_length=200 directory=documents extensions=[pdfdoc] blank=True null=True)

FileBrowseField in Templates

You can use all attributes from FileObject

blogentryimage ltimg src= publicationimageurl gt

ifequal blogentryimageimage_orientation landscape ltimg src= blogentryimageurl class=landscape gt

endifequal

19

Django FileBrowser Documentation Release 357

Showing Thumbnail in the Changelist

To show a thumbnail with the changelist you can define a ModelAdmin method

from filebrowsersettings import ADMIN_THUMBNAIL

def image_thumbnail(self obj)if objimage and objimagefiletype == Image

return ltimg src=s gt objimageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Using the FileBrowseField with TinyMCE

In order to replace the TinyMCE imagefile manager with the FileBrowser you have to use a FileBrowser CallbackTherersquos an example TinyMCE configuration file in staticjs called TinyMCEAdminjs You can either copy theFileBrowserCallback to your own file or just use tinymce_setupjs (which comes with django-grappelli)

Just add these lines to your ModelAdmin asset definitions

class Mediajs = [pathtotinymcejscriptstiny_mcetiny_mcejs

pathtoyourtinymce_setupjs]

312 FileInput

Subclass of FileInput with an additional thumbnail

from filebrowserwidgets import FileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget FileInput

313 ClearableFileInput

Subclass of ClearableFileInput with an additional thumbnail

from filebrowserwidgets import ClearableFileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget ClearableFileInput

314 Django FileField and the FileBrowser

Return a FileObject from a FileField or ImageField with

20 Chapter 3 Fields amp Widgets

Django FileBrowser Documentation Release 357

from filebrowserbase import FileObject

image_upload = modelsImageField(uImage (Upload) max_length=250 upload_to=image_upload_path blank=True null=True)

def image(self)if selfimage_upload

return FileObject(selfimage_uploadpath)return None

In order show a thumbnail with your changelist you could use a ModelAdmin method

from filebrowserbase import FileObject

def image_thumbnail(self obj)if objimage_upload

image = FileObject(objimage_uploadpath)if imagefiletype == Image

return ltimg src=s gt imageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Note There are different ways to achieve this The above examples show one of several options

31 Fields amp Widgets 21

Django FileBrowser Documentation Release 357

22 Chapter 3 Fields amp Widgets

CHAPTER 4

Admin Interface

41 Admin Interface

The main FileBrowser admin application is an extension for the Django admin interface in order to browser yourmedia folder upload and renamedelete files

411 FileBrowser Site

New in version 340

class FileBrowserSite(name=None app_name=rsquofilebrowserrsquo storage=default_storage)Respresents the FileBrowser admin application (similar to Djangorsquos admin site)

Parameters

bull name ndash A name for the site defaults to None

bull app_name ndash Defaults to lsquofilebrowserrsquo

bull storage ndash A custom storage engine defaults to Djangos default storage

Similar to djangocontribadmin you first need to add a filebrowsersite to your admin interface Inyour urlspy import the default FileBrowser site (or your custom site) and add the site to your URL-patterns (beforeany admin-urls)

from filebrowsersites import site

urlpatterns = patterns(url(r^adminurlfilebrowser include(siteurls))

)

Now you are able to browse the location defined with the storage engine associated to your site

from djangocorefilesstorage import DefaultStoragefrom filebrowsersites import FileBrowserSite

Default FileBrowser sitesite = FileBrowserSite(name=filebrowser storage=DefaultStorage())

My Custom FileBrowser sitecustom_site = FileBrowserSite(name=custom_filebrowser storage=DefaultStorage())custom_sitedirectory = custom_uploads

23

Django FileBrowser Documentation Release 357

Note The module variable site from filebrowsersites is the default FileBrowser application

412 Custom Actions

New in version 340

Similar to Djangorsquos admin actions you can define your FileBrowser actions and thus automate the typical tasks ofyour users Registered custom actions are listed in the detail view of a file and a user can select a single action at atime The selected action will then be applied to the file

The default FileBrowser image actions such as ldquoFlip Verticalrdquo or ldquoRotate 90deg Clockwiserdquo are in fact implemented ascustom actions (see the module filebrowseractions)

Writing Your Own Actions

Custom actions are simple functions

def foo(request fileobjects) Do something with the fileobjects

The first parameter is a HttpRequest object (representing the submitted form in which a user selected the action)and the second parameter is a list of FileObjects to which the action should be applied

The list contains exactly one instance of FileObject (representing the file from the detail view) but this may change inthe future as custom actions may become available also in browse views (similar to admin actions applied to a list ofchecked objects)

Registering an Action

In order to make your action visible you need to register it with a FileBrowser site

siteadd_action(foo)

Once registered the action will appear in the detail view of a file You can also give your action a short description

fooshort_description = Do foo with the File

This short description will then appear in the list of available actions If you do not provide a short description thefunction name will be used instead and FileBrowser will replace any underscores in the function name with spaces

Associating Actions with Specific Files

Each custom action can be associated with a specific file type (eg images audio file etc) to which it applies In orderto do that you need to define a predicatefilter function which takes a single argument (FileObject) and returns Trueif your action is applicable to that FileObject Finally you need to register this filter function with your action

fooapplies_to(lambda fileobject fileobjectfiletype == Image)

In the above example foo will appear in the action list only for image files If you do not specify any filter functionfor your action FileBrowser considers the action as applicable to all files

24 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

Messages amp Intermediate Pages

You can provide a feedback to a user about a successful or failed execution of an action by using a message Forexample

from djangocontrib import messages

def desaturate_image(request fileobjects)for f in fileobjects

Desaturate the imagemessagesadd_message(request messagesSUCCESS _(Image s was desaturated) ffilename)

Some actions may require user confirmation (eg in order to prevent accidental and irreversible modification tofiles) In order to that follow the same pattern as with Djangorsquos admin action and return a HttpResponse objectfrom your action Good practice for intermediate pages is to implement a confirm view and have your action returnHttpResponseRedirect

def crop_image(request fileobjects)files = ampf=join([fpath_relative for f in fileobjects])return HttpResponseRedirect(confirmaction=crop_imageampf=s files)

413 File Storages

New in version 340

You have the option to specify which file storage engine a FileBrowser should use to browseuploadmodify yourmedia files This enables you to use a FileBrowser even if your media files are located at some remote system Seealso the Djangorsquos documentation on storages httpsdocsdjangoprojectcomendevtopicsfiles

To associate a FileBrowser site with a particular storage engine set the storage property of a site object

from djangocorefilesstorage import FileSystemStoragesitestorage = FileSystemStorage(location=pathtomediadirectory base_url=media)

For storage classes other than FileSystemStorage (or those that inherit from that class) therersquos more effort involved inproviding a storage object that can be used with FileBrowser See StorageMixin Class

Note Prior FileBrowser 34 the way to specify FileBrowserlsquos MEDIA_ROOT and MEDIA_URL was via settingspyStarting from version 34 those variables are associated with the storage instance and you can set them as illustratedin the above example

Warning For the reason of backward compatibility FileBrowser settings FILEBROWSER_MEDIA_ROOT andFILEBROWSER_MEDIA_URL can still be used to customize FileBrowser as long as yoursquore using the defaultFileBrowserlsquos site without having changed its storage engine In the next major release of FileBrowser thesesettings will be removed

StorageMixin Class

A FileBrowser uses the Djangorsquos Storage class to access media files However the API of the Storageclass does not provide all methods necessary for FileBrowserrsquos functionality A StorageMixin class fromfilebrowserstorage module therefore defines all the additional methods that a FileBrowser requires

isdir(self name)Returns true if name exists and is a directory

41 Admin Interface 25

Django FileBrowser Documentation Release 357

isfile(self name)Returns true if name exists and is a regular file

move(self old_file_name new_file_name allow_overwrite=False)Moves safely a file from one location to another If allow_ovewrite==False and new_file_nameexists raises an exception

makedirs(self name)Creates all missing directories specified by name Analogue to osmkdirs()

414 Views

All views use the staff_member_requird and path_exists decorator in order to check if the server pathactually exists Some views also use the file_exists decorator

bull Browse fb_browse Browse a directory on your server Returns a FileListing

ndash Optional query string args dir o ot q p filter_date filter_type type

bull Create directory fb_createdir Create a new folder on your server

ndash Optional query string args dir

ndash Signals filebrowser_pre_createdir filebrowser_post_createdir

bull Upload fb_upload Multiple upload

ndash Optional query string args dir type

ndash Signals filebrowser_pre_upload filebrowser_post_upload

bull Edit fb_edit Edit a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_rename filebrowser_post_rename

You are able to apply custom actions (see Custom Actions) to the edit-view

bull Confirm delete fb_confirm_delete Confirm the deletion of a file or folder

ndash Required query string args filename

ndash Optional query string args dir

If you try to delete a folder all filesfolders within this folder are listed on this page

bull Delete fb_delete Delete a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_delete filebrowser_post_delete

Warning If you delete a Folder all items within this Folder are being deleted

bull Version fb_version Generate a version of an image as defined with ADMIN_VERSIONS

ndash Required query string args filename

ndash Optional Query string args dir

This is a helper used by the FileBrowseField and TinyMCE for selecting a version

26 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

415 Signals

The FileBrowser sends a couple of different signals Please take a look at the module filebrowsersignals for furtherexplanation on the provided arguments

bull filebrowser_pre_upload Sent before a an Upload starts

bull filebrowser_post_upload Sent after an Upload has finished

bull filebrowser_pre_delete Sent before an Item (File Folder) is deleted

bull filebrowser_post_delete Sent after an Item (File Folder) has been deleted

bull filebrowser_pre_createdir Sent before a new Folder is created

bull filebrowser_post_createdir Sent after a new Folder has been created

bull filebrowser_pre_rename Sent before an Item (File Folder) is renamed

bull filebrowser_post_rename Sent after an Item (File Folder) has been renamed

bull filebrowser_actions_pre_apply Sent before a custom action is applied

bull filebrowser_actions_post_apply Sent after a custom action has been applied

Example for using these Signals

Herersquos a small example for using the above Signals

from filebrowser import signals

def pre_upload_callback(sender kwargs)Receiver function called before an upload startsprint Pre Upload Callbackprint kwargs kwargs

signalsfilebrowser_pre_uploadconnect(pre_upload_callback)

def post_upload_callback(sender kwargs)Receiver function called each time an upload has finishedprint Post Upload Callbackprint kwargs kwargs You can use all attributes available with the FileObject This is just an example print Filesize kwargs[file]filesizeprint Orientation kwargs[file]orientationprint Extension kwargs[file]extension

signalsfilebrowser_post_uploadconnect(post_upload_callback)

41 Admin Interface 27

Django FileBrowser Documentation Release 357

28 Chapter 4 Admin Interface

CHAPTER 5

Image Versions

51 Versions

With the FileBrowser you are able to define different versionssizes for images This enables you to save an originalimage on your server while having different versions of that image to automatically fit your websites grid Versionsare also useful for responsiveadaptive layouts

511 Defining Versions

New in version 340 methods

First you need to know which versionssizes of an image yoursquod like to generate with your website Letrsquos say yoursquoreusing a 12 column grid with 60px for each column and 20px margin (which is a total of 940px) With this grid youcould (for example) define these image versions

FILEBROWSER_VERSIONS_BASEDIR = _versionsFILEBROWSER_VERSIONS =

admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

Use the methods argument if you need to add a filter

def grayscale(im)Convert image to grayscaleif immode = L

im = imconvert(L)return im

FILEBROWSER_VERSIONS = big verbose_name Big (6 col) width 460 height opts methods [grayscale]

)

29

Django FileBrowser Documentation Release 357

512 Versions and the Admin

When using the FileBrowser with the admin interface you need to define ADMIN_VERSIONS andADMIN_THUMBNAIL (see Settings) ADMIN_VERSIONS are available with the admin ie you are able to seethese versions with the image detail view and you are able to select the versions with the FileBrowseField model field

FILEBROWSER_ADMIN_VERSIONS = [thumbnail small medium big large]FILEBROWSER_ADMIN_THUMBNAIL = admin_thumbnail

513 Versions and the Frontend

With your templates you have two different tags to choose from version and version_object With bothtags the version will be generated if it doesnrsquot already exist OR if the original image is newer than the version Inorder to update an image you just overwrite the original image and the versions will be generated automatically (asyou request them within your template)

A Model example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 blank=True null=True)

With your templates use version if you simply need to retrieve the URL or version_object if you need to geta FileObject

lt-- load filebrowser templatetags --gt load fb_versions

lt-- get the url with version --gtltimg src= version blogentryimage medium gt

lt-- get a fileobject with version_object --gt version_object blogentryimage medium as version_medium version_mediumwidth ltimg src= version_medium gt

Templatetag version

RetrievesGenerates a version and returns an URL

version modelfield_name version_prefix

Templatetag version_object

RetrievesGenerates a version and returns a FileObject

version_object modelfield_name version_prefix as variable

Note With both templatetags version_prefix can either be a string or a variable If version_prefix is astring use quotes

30 Chapter 5 Image Versions

Django FileBrowser Documentation Release 357

514 Versions in Views

If you have a FileObject you can generateretrieve a version with

v = objimageversion_generate(version_prefix) returns a FileObject

515 Placeholder

When developing on a locale machine or a development-server you might not have all the images (resp media-files)available that are on your production instance and downloading these files on a regular basis might not be an option

In that case you can use a placeholder instead of a version You just need to define the PLACEHOLDER and overwritethe settings SHOW_PLACEHOLDER andor FORCE_PLACEHOLDER (see Placeholder)

516 Management Commands

fb_version_generateIf you need to generate certain (or all) versions type

python managepy fb_version_generate

fb_version_removeIf you need to generate certain (or all) versions type

python managepy fb_version_generate

Warning Please be very careful with this command

51 Versions 31

Django FileBrowser Documentation Release 357

32 Chapter 5 Image Versions

CHAPTER 6

Help

61 Help

611 FAQ

Why should I use the FileBrowser

If you need your editors or customers to manage files the FileBrowser is an alternative to an FTP-client Moreoveryou are able to define different image versions according to your websites grid Alternatives to the FileBrowser can befound at httpdjangopackagescomgridsgfile-managers

Do I need Grappelli

Grappelli is a requirement for using the FileBrowser There are several filebrowser-no-grappelli repositories (most ofthem on GitHub) but we donrsquot follow the development

I need help

see Troubleshooting

Why are there no fancy effects

The FileBrowser is about managing files We think that you should prepare your files before uploading them to theserver

How do I upload to another server

Use a custom storage engine see httpsdocsdjangoprojectcomen16howtocustom-file-storage

Why do I need image-versions

You need image-versions if your website is based on a grid

33

Django FileBrowser Documentation Release 357

Is the FileBrowser stable

Wersquove developed the FileBrowser for a couple of years and use it with almost all of our clients That said Grappelli isthe more stable and mature application

How can I contribute

Help is very much needed and appreciated Test the FileBrowser and submit feedbackpatches

Who develops the FileBrowser

The FileBrowser is developed and maintained by Patrick Kranzlmuumlller amp Axel Swoboda of vonautomatisch

612 Troubleshooting

Check your setup

Please check if the problem is caused by your setup

bull Read Quick start guide

bull Check if the staticmedia-files are served correctly

bull Make sure you have removed all custom FileBrowser templates from all locations in TEMPLATE_DIRS orcheck that these templates are compatible with the FileBrowser

Run the tests

Start the shell and type

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Check issues

If your setup is fine please check if your problem is a known issue

bull Take a look at all FileBrowser Issues (incuding closed) and search the FileBrowser Google-Group

Add a ticket

If you think yoursquove found a bug please add a ticket

bull Try to describe your problem as precisely as possible

bull Tell us what you did in order to solve the problem

bull Tell us what version of the FileBrowser you are using

bull Tell us what version of Django you are using

34 Chapter 6 Help

Django FileBrowser Documentation Release 357

bull Please do NOT add tickets if yoursquore having problems with serving staticmedia-files (because this is not relatedto the FileBrowser)

bull Please do NOT add tickets referring to Djangos trunk version

bull At best add a patch

Note Be aware that we may close issues not following these guidlines without further notifications

613 Translation

Translation is done via Transifex

Supported Languages

see httpswwwtransifexnetprojectspdjango-filebrowserresourcedjangopo

614 FileBrowser 35 Release Notes

FileBrowser 35 is compatible with Django 14151617 as well as Grappelli 242526

Update from FileBrowser 34x

bull Update Django to 14151617 and check httpsdocsdjangoprojectcomendevreleases14 orhttpsdocsdjangoprojectcomendevreleases15 or httpsdocsdjangoprojectcomendevreleases16

bull Update Grappelli to 24x25x26x

bull Update FileBrowser to 35x

62 Changelog

621 358 (not yet released)

622 357 (September 10th 2014)

bull New Compatibility with Django 17 and Grappelli 26x

bull Improved Updated tests because of the new random suffix with get_available_name (django storage)

bull Improved Added an icon in order to mark finished uploads

bull Improved Show resulting filename (eg with suffix converted) after successful upload

bull Fixed Permissions with file upload

bull Fixed Unified json response with _upload_file (no matter if file already exists or not)

623 356 (April 16th 2014)

bull Fixed Displaying pagination correctly with lots of entries

62 Changelog 35

Django FileBrowser Documentation Release 357

624 355 (April 13th 2014)

bull New Added client-side (JavaScript) file extension validation to the AJAX uploader

bull New Added experimental Python 33 support

bull Improved Tests with convertnormalize (removed special chars from test filename)

bull Fixed File selection after using search box (CKEditor)

bull Fixed Removed encoding of file URIs with CKEditor

625 354 (February 21st 2014)

bull Fixed Placeholder functionality (including tests)

bull Fixed Convertnormalize filenames (including tests)

bull Fixed Handling uppercase extensions with browse

626 353 (January 7 2014)

bull New added path_full to FileObject

bull Improved added docx to EXTENSIONS

bull Improved Recommend pillow instead of PIL as a requirement

bull Improved Added additional test cases

bull Improved Updated documentation

bull Improved Consistent use of storage (eg storagelocation storageurl)

bull Improved Removed unnecessary functions (eg url_join url_strip)

bull Improved Moved sort_by_attr to FileListing

bull Improved Regex matches with file versions on browse

bull Improved Using djangoconfurls (with djangoconfurlsdefaults as fallback)

bull Improved Adding CONTRIBUTINGrst

bull Improved Removed static Media inner class with fields

bull Improved Removed search icon with fields (has not being used)

bull Improved Added custom class attributes with filebrowser field

bull Improved Updated translations

bull Fixed fixed exception handling with python 25

bull Fixed fixes dir with SEARCH_TRAVERSE true and version select

bull Fixed Make Django FileUploadHandlers work (also fixed a memory leak)

bull Fixed return correct filename with OVERWRITE_EXISTING

bull Fixed fb_version_generate with FILEBROWSER_VERSIONS_BASEDIR

bull Fixed Table sorting with ascdesc

bull Fixed Added DeprecationWarning for FileObjectdirectory and FileObjectfolder

36 Chapter 6 Help

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

CHAPTER 1

Installation and Setup

11 Quick start guide

For using the FileBrowser Django needs to be installed and an Admin Site has to be activated

111 Requirements

bull Django 14151617 httpwwwdjangoprojectcom

bull Grappelli 242526 httpsgithubcomsehmaschinedjango-grappelli

bull Pillow httpsgithubcompython-imagingPillow

112 Installation

Install the FileBrowser

pip install django-filebrowser

Add the filebrowser to your INSTALLED_APPS (before djangocontribadmin)

INSTALLED_APPS = (grappellifilebrowserdjangocontribadmin

)

Add the FileBrowser site to your url-patterns (before any admin-urls)

from filebrowsersites import site

urlpatterns = patterns((r^adminfilebrowser include(siteurls))(r^grappelli include(grappelliurls))(r^admin include(adminsiteurls))

)

Collect the static files (please refer to the Staticfiles Documentation for more information)

python managepy collectstatic

3

Django FileBrowser Documentation Release 357

113 Settings

Check the Settings

Note You need to add a folder ldquouploadsrdquo within sitestoragelocation when using the default settingsAnd we strongly recommend to define a VERSIONS_BASEDIR

114 Testing

Run the FileBrowser tests

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Start the devserver and login to your admin site

python managepy runserver ltIP-addressgt8000

Goto adminfilebrowserbrowse and check if everything looksworks as expected If yoursquore having problems seeTroubleshooting

12 Settings

There are some settings in order to customize the FileBrowser Nonetheless you should be able to start with the defaultsettings

All settings can be defined in your projects settings-file In that case you have to use the prefix FILEBROWSER_ forevery setting (eg FILEBROWSER_EXTENSIONS instead of EXTENSIONS)

121 Main URLPaths Settings

MEDIA_ROOT

Warning Will be removed with version 360 Since 34 MEDIA_ROOT is defined with your storage engine

The absolute path to the directory that holds the media-files you want to browse

MEDIA_ROOT = getattr(settings FILEBROWSER_MEDIA_ROOT settingsMEDIA_ROOT)

MEDIA_URL

Warning Will be removed with version 360 Since 34 MEDIA_URL is defined with your storage engine

URL that handles the media served from MEDIA_ROOT

MEDIA_URL = getattr(settings FILEBROWSER_MEDIA_URL settingsMEDIA_URL)

4 Chapter 1 Installation and Setup

Django FileBrowser Documentation Release 357

DIRECTORY (relative to storage location)

Main FileBrowser Directory Leave empty in order to browse all files and folders within a storage location

DIRECTORY = getattr(settings FILEBROWSER_DIRECTORY uploads)

You can override this setting on a perndashsite basis

from filebrowsersites import sitesitedirectory = uploads

122 FileBrowser Media TinyMCE Media

Deprecated since version 353 Use staticfiles instead

123 Extensions and Formats

EXTENSIONS

Allowed extensions for file upload

EXTENSIONS = getattr(settings FILEBROWSER_EXTENSIONS Folder []Image [jpgjpeggifpngtiftiff]Document [pdfdocrtftxtxlscsv]Video [movwmvmpegmpgavirm]Audio [mp3mp4wavaiffmidim4p]

)

SELECT_FORMATS

Set different Options for selecting elements from the FileBrowser

SELECT_FORMATS = getattr(settings FILEBROWSER_SELECT_FORMATS file [FolderImageDocumentVideoAudio]image [Image]document [Document]media [VideoAudio]

)

When using the browse-function for selecting FilesFolders you can use an additional query-attribute type in orderto restrict the choices

124 Versions

VERSIONS_BASEDIR (relative to storage location)

Changed in version 340

Directory to save image versions (and thumbnails) If no directory is given versions are stored at the same location asthe original image

12 Settings 5

Django FileBrowser Documentation Release 357

VERSIONS_BASEDIR = getattr(settings FILEBROWSER_VERSIONS_BASEDIR )

We do recommend the following structure for media files

-- media sitestoragelocation (eg MEDIA_ROOT)-- _versions VERSIONS_BASEDIR (outside of sitedirectory)-- uploads sitedirectory

Warning If VERSIONS_BASEDIR is within sitedirectory it will be browsed

Warning With the next major release (360) the default setting will be ldquo_versionsrdquo

VERSIONS

Define the versions according to your websites grid

VERSIONS = getattr(settings FILEBROWSER_VERSIONS admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

)

VERSION_QUALITY

Quality of saved versions

VERSION_QUALITY = getattr(settings FILEBROWSER_VERSION_QUALITY 90)

ADMIN_VERSIONS

The versions you want to show with the admin interface

ADMIN_VERSIONS = getattr(settings FILEBROWSER_ADMIN_VERSIONS [thumbnail small medium big large])

ADMIN_THUMBNAIL

The version being used as the admin thumbnail

ADMIN_THUMBNAIL = getattr(settings FILEBROWSER_ADMIN_THUMBNAIL admin_thumbnail)

125 Placeholder

With your locale environment you donrsquot necessarily have access to all media files (eg images uploaded by yourclient) Therefore you can use a PLACEHOLDER

6 Chapter 1 Installation and Setup

Django FileBrowser Documentation Release 357

PLACEHOLDER

Path to placeholder image (relative to storage location)

PLACEHOLDER = getattr(settings FILEBROWSER_PLACEHOLDER )

SHOW_PLACEHOLDER

Show placeholder (instead of a version) if the original image does not exist

SHOW_PLACEHOLDER = getattr(settings FILEBROWSER_SHOW_PLACEHOLDER False)

FORCE_PLACEHOLDER

Always show placeholder (even if the original image exists)

FORCE_PLACEHOLDER = getattr(settings FILEBROWSER_FORCE_PLACEHOLDER False)

126 Extra Settings

SAVE_FULL_URL

Deprecated since version 340 With custom storage engines saving the full URL doesnrsquot make sense anymoreMoreover removing this settings allows for easily replacing a FileBrowseField with Djangos File- or ImageField

STRICT_PIL

If set to True the FileBrowser will not try to import a mis-installed PIL

STRICT_PIL = getattr(settings FILEBROWSER_STRICT_PIL False)

IMAGE_MAXBLOCK

see httpmailpythonorgpipermailimage-sig1999-August000816html

IMAGE_MAXBLOCK = getattr(settings FILEBROWSER_IMAGE_MAXBLOCK 10241024)

EXCLUDE

Exclude-patterns for files you donrsquot want to show

EXTENSION_LIST = []for exts in EXTENSIONSvalues()

EXTENSION_LIST += extsEXCLUDE = getattr(settings FILEBROWSER_EXCLUDE (r_((exts)s)__qd13((exts)s) exts (|join(EXTENSION_LIST))))

12 Settings 7

Django FileBrowser Documentation Release 357

MAX_UPLOAD_SIZE

Max Upload Size in Bytes

MAX_UPLOAD_SIZE = getattr(settings FILEBROWSER_MAX_UPLOAD_SIZE 10485760)

NORMALIZE_FILENAME

True if you want to normalize filename on upload and remove all non-alphanumeric characters (except for under-scores spaces amp dashes)

NORMALIZE_FILENAME = getattr(settings FILEBROWSER_NORMALIZE_FILENAME False)

CONVERT_FILENAME

True if you want to convert the filename on upload (replace spaces and convert to lowercase)

CONVERT_FILENAME = getattr(settings FILEBROWSER_CONVERT_FILENAME True)

LIST_PER_PAGE

How many items appear on each paginated list

LIST_PER_PAGE = getattr(settings FILEBROWSER_LIST_PER_PAGE 50)

DEFAULT_SORTING_BY

Default sorting attribute

DEFAULT_SORTING_BY = getattr(settings FILEBROWSER_DEFAULT_SORTING_BY date)

Options are date filesize filename_lower filetype_checked

DEFAULT_SORTING_ORDER

Default sorting order

DEFAULT_SORTING_ORDER = getattr(settings FILEBROWSER_DEFAULT_SORTING_ORDER desc)

Options are asc or desc

FOLDER_REGEX

regex to clean directory names before creation

FOLDER_REGEX = getattr(settings FILEBROWSER_FOLDER_REGEX r^[w_ -]+$)

8 Chapter 1 Installation and Setup

Django FileBrowser Documentation Release 357

SEARCH_TRAVERSE

True if you want to traverse all subdirectories when searching Please note that with thousands of filesdirectoriesthis might take a while

SEARCH_TRAVERSE = getattr(settings FILEBROWSER_SEARCH_TRAVERSE False)

DEFAULT_PERMISSIONS

Default upload and version permissions

DEFAULT_PERMISSIONS = getattr(settings FILEBROWSER_DEFAULT_PERMISSIONS 0755)

OVERWRITE_EXISTING

New in version 351

True in order to overwrite existing files False to use the behaviour of the storage engine

OVERWRITE_EXISTING = getattr(settings FILEBROWSER_OVERWRITE_EXISTING True)

12 Settings 9

Django FileBrowser Documentation Release 357

10 Chapter 1 Installation and Setup

CHAPTER 2

API

21 API

211 FileListing

class FileListing(path filter_func=None sorting_by=None sorting_order=None)Returns a list of FileObjects for a server path see FileObject

Parameters

bull path ndash Relative path to a location within sitestoragelocation

bull filter_func ndash Filter function see example below

bull sorting_by ndash Sort the files by any attribute of FileObject

bull sorting_order ndash Sorting order either ldquoascrdquo or ldquodescrdquo

If you want to list all files within a storage location you do

from filebrowsersites import sitefrom filebrowserbase import FileListingfilelisting = FileListing(sitestoragelocation sorting_by=date sorting_order=desc)

Use a custom filter function to limit the list of files

def filter_filelisting(item) item is a FileObjectreturn itemfiletype = Folder

filelisting = FileListing(sitestoragelocation filter_func=filter_listing sorting_by=date sorting_order=desc)

Methods

For the below examples wersquore using this folder-structure

mediauploadstestfoldertestimagejpgmediauploadsblog1imagesblogimagejpg

Note We defined filter_browse as filter_func (see sitespy) And we did not define aVERSIONS_BASEDIR for this demonstration though it is highly recommended to use one

11

Django FileBrowser Documentation Release 357

listing()Returns all items for the given path with oslistdir(path)

gtgtgt for item in filelistinglisting() print itemblogtestfolder

walk()Returns all items for the given path with oswalk(path)

gtgtgt for item in filelistingwalk() print itemblogblog1blog1imagesblog1imagesblogimagejpgblog1imagesblogimage_admin_thumbnailjpgblog1imagesblogimage_mediumjpgblog1imagesblogimage_smalljpgblog1imagesblogimage_thumbnailjpgtestfoldertestfoldertestimagejpg

files_listing_total()Returns a sorted list of FileObjects for listing()

gtgtgt for item in filelistingfiles_listing_total() print itemuploadsbloguploadstestfolder

files_walk_total()Returns a sorted list of FileObjects for walk()

gtgtgt for item in filelistingfiles_walk_total() print itemuploadsbloguploadsblog1uploadsblog1imagesuploadsblog1imagesblogimagejpguploadsblog1imagesblogimage_admin_thumbnailjpguploadsblog1imagesblogimage_mediumjpguploadsblog1imagesblogimage_smalljpguploadsblog1imagesblogimage_thumbnailjpguploadstestfolderuploadstestfoldertestimagejpg

files_listing_filtered()Returns a sorted and filtered list of FileObjects for listing()

gtgtgt for item in filelistingfiles_listing_filtered() print itemuploadsbloguploadstestfolder

files_walk_filtered()Returns a sorted and filtered list of FileObjects for walk()

12 Chapter 2 API

Django FileBrowser Documentation Release 357

gtgtgt for item in filelistingfiles_walk_filtered() print itemuploadsbloguploadsblog1uploadsblog1imagesuploadsblog1imagesblogimagejpguploadstestfolderuploadstestfoldertestimagejpg

Note The versions are not listed (compared with files_walk_total) because of filter_func

results_listing_total()Number of total files based on files_listing_total()

gtgtgt filelistingresults_listing_total()2

results_walk_total()Number of total files based on files_walk_total()

gtgtgt filelistingresults_walk_total()10

results_listing_filtered()Number of filtered files based on files_listing_filtered()

gtgtgt filelistingresults_listing_filtered()2

results_walk_filtered()Number of filtered files based on files_walk_filtered()

gtgtgt filelistingresults_walk_filtered()6

212 FileObject

class FileObject(path site=None)An object representing a media file

Parameters

bull path ndash Relative path to a location within sitestoragelocation

bull site ndash An optional FileBrowser Site

For example

from filebrowsersites import sitefrom filebrowserbase import FileObjectfileobject = FileObject(ospathjoin(sitedirectorytestfoldertestimagejpg))version = FileObject(ospathjoin(fileobjectversions_basedir testfolder testimage_mediumjpg))

21 API 13

Django FileBrowser Documentation Release 357

Attributes

Initial Attributes

pathPath relative to a storage location (including sitedirectory)

gtgtgt fileobjectpathuploadstestfoldertestimagejpg

headThe directory name of pathname path

gtgtgt fileobjectheaduploadstestfolder

filenameName of the file (including the extension) or name of the folder

gtgtgt fileobjectfilenametestimagejpg

filename_lowerLower type of filename

filename_rootFilename without extension

gtgtgt fileobjectfilename_roottestimage

extensionFile extension including the dot With a folder the extensions is None

gtgtgt fileobjectextensionjpg

mimetypeMimetype based on httpdocspythonorglibrarymimetypeshtml

gtgtgt fileobjectmimetype(imagejpeg None)

General Attributes

filetypeType of the file as defined with EXTENSIONS

gtgtgt fileobjectfiletypeImage

filesizeFilesize in Bytes

gtgtgt fileobjectfilesize870037L

14 Chapter 2 API

Django FileBrowser Documentation Release 357

dateDate based on timemktime

gtgtgt fileobjectdate12997603470

datetimeDatetime object

gtgtgt fileobjectdatetimedatetimedatetime(2011 3 10 13 32 27)

existsTrue if the path exists False otherwise

gtgtgt fileobjectexistsTrue

Path and URL attributes

pathPath relative to a storage location (including sitedirectory)

gtgtgt fileobjectpathuploadstestfoldertestimagejpg

path_relative_directoryPath relative to sitedirectory

gtgtgt fileobjectpath_relative_directorytestfoldertestimagejpg

path_fullAbsolute server path (based on storagepath)

gtgtgt fileobjectpath_fullabsolutepathtoserverlocationtestfoldertestimagejpg

dirnameNew in version 34

The directory (not including sitedirectory)

gtgtgt fileobjectdirnametestfolder

urlURL for the filefolder (based on storageurl)

gtgtgt fileobjecturlmediauploadstestfoldertestimagejpg

Image attributes

The image attributes are only useful if the FileObject represents an image

dimensionsImage dimensions as a tuple

21 API 15

Django FileBrowser Documentation Release 357

gtgtgt fileobjectdimensions(1000 750)

widthImage width in px

gtgtgt fileobjectwidth1000

heightImage height in px

gtgtgt fileobjectheight750

aspectratioAspect ratio (float format)

gtgtgt fileobjectaspectratio133534908

orientationImage orientation either Landscape or Portrait

gtgtgt fileobjectorientationLandscape

Folder attributes

The folder attributes make sense when the FileObject represents a directory (not a file)

directory

Deprecated since version 353 Use path_relative_directory instead

folder

Deprecated since version 353 Use dirname instead

is_folderTrue if path is a folder

gtgtgt fileobjectis_folderFalse

is_emptyTrue if the folder is empty False if the folder is not empty or the FileObject is not a folder

gtgtgt fileobjectis_emptyFalse

Version attributes

is_versiontrue if the File is a version of another File

16 Chapter 2 API

Django FileBrowser Documentation Release 357

gtgtgt fileobjectis_versionFalsegtgtgt versionis_versionTrue

versions_basedirThe relative path (from storage location) to the main versions folder Either VERSIONS_BASEDIR orsitedirectory

gtgtgt fileobjectversions_basedir_versionsgtgtgt versionversions_basedir_versions

originalReturns the original FileObject

gtgtgt fileobjectoriginalltFileObject uploadstestfoldertestimagejpggtgtgtgt versionoriginalltFileObject uploadstestfoldertestimagejpggt

original_filenameGet the filename of an original image from a version

gtgtgt fileobjectoriginal_filenametestimagejpggtgtgt versionoriginal_filenametestimagejpg

Methods

Version methods

versions()List all filenames based on VERSIONS

gtgtgt fileobjectversions()[_versionstestfoldertestimage_admin_thumbnailjpg_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionversions()[]

Note The versions are not being generated

admin_versions()List all filenames based on ADMIN_VERSIONS

gtgtgt fileobjectadmin_versions()[_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg

21 API 17

Django FileBrowser Documentation Release 357

_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionadmin_versions()[]

Note The versions are not being generated

version_name(version_suffix)Get the filename for a version

gtgtgt fileobjectversion_name(medium)testimage_mediumjpg

Note The version is not being generated

version_path(version_suffix)Get the path for a version

gtgtgt fileobjectversion_path(medium)_versionstestfoldertestimage_mediumjpg

Note The version is not being generated

version_generate(version_suffix)Generate a version

gtgtgt fileobjectversion_generate(medium)ltFileObject uploadstestfoldertestimage_mediumjpggt

Please note that a version is only generated if it does not already exist or if the original image is newer than theexisting version

Delete methods

delete()Delete the File or Folder from the server

Warning If you delete a Folder all items within the folder are being deleted

delete_versions()Delete all VERSIONS

delete_admin_versions()Delete all ADMIN_VERSIONS

18 Chapter 2 API

CHAPTER 3

Fields amp Widgets

31 Fields amp Widgets

The FileBrowseField is a custom model field which returns a FileObject The widgets FileInput and ClearableFileIn-put are used with the admin app in order to show an additional thumbnail for images

311 FileBrowseField

class FileBrowseField(max_length[ site directory extensions format options])A subclass of CharField referencing a media file within Returns a FileObject

Parameters

bull site ndash A FileBrowser site (defaults to the main site) see FileBrowser Site

bull directory ndash Directory to browse when clicking the search icon

bull extensions ndash List of allowed extensions see Extensions and Formats

bull format ndash A key from SELECT_FORMATS in order to restrict the selection to specificfiletypes see Extensions and Formats

For example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 directory=images extensions=[jpg] blank=True null=True)document = FileBrowseField(PDF max_length=200 directory=documents extensions=[pdfdoc] blank=True null=True)

FileBrowseField in Templates

You can use all attributes from FileObject

blogentryimage ltimg src= publicationimageurl gt

ifequal blogentryimageimage_orientation landscape ltimg src= blogentryimageurl class=landscape gt

endifequal

19

Django FileBrowser Documentation Release 357

Showing Thumbnail in the Changelist

To show a thumbnail with the changelist you can define a ModelAdmin method

from filebrowsersettings import ADMIN_THUMBNAIL

def image_thumbnail(self obj)if objimage and objimagefiletype == Image

return ltimg src=s gt objimageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Using the FileBrowseField with TinyMCE

In order to replace the TinyMCE imagefile manager with the FileBrowser you have to use a FileBrowser CallbackTherersquos an example TinyMCE configuration file in staticjs called TinyMCEAdminjs You can either copy theFileBrowserCallback to your own file or just use tinymce_setupjs (which comes with django-grappelli)

Just add these lines to your ModelAdmin asset definitions

class Mediajs = [pathtotinymcejscriptstiny_mcetiny_mcejs

pathtoyourtinymce_setupjs]

312 FileInput

Subclass of FileInput with an additional thumbnail

from filebrowserwidgets import FileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget FileInput

313 ClearableFileInput

Subclass of ClearableFileInput with an additional thumbnail

from filebrowserwidgets import ClearableFileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget ClearableFileInput

314 Django FileField and the FileBrowser

Return a FileObject from a FileField or ImageField with

20 Chapter 3 Fields amp Widgets

Django FileBrowser Documentation Release 357

from filebrowserbase import FileObject

image_upload = modelsImageField(uImage (Upload) max_length=250 upload_to=image_upload_path blank=True null=True)

def image(self)if selfimage_upload

return FileObject(selfimage_uploadpath)return None

In order show a thumbnail with your changelist you could use a ModelAdmin method

from filebrowserbase import FileObject

def image_thumbnail(self obj)if objimage_upload

image = FileObject(objimage_uploadpath)if imagefiletype == Image

return ltimg src=s gt imageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Note There are different ways to achieve this The above examples show one of several options

31 Fields amp Widgets 21

Django FileBrowser Documentation Release 357

22 Chapter 3 Fields amp Widgets

CHAPTER 4

Admin Interface

41 Admin Interface

The main FileBrowser admin application is an extension for the Django admin interface in order to browser yourmedia folder upload and renamedelete files

411 FileBrowser Site

New in version 340

class FileBrowserSite(name=None app_name=rsquofilebrowserrsquo storage=default_storage)Respresents the FileBrowser admin application (similar to Djangorsquos admin site)

Parameters

bull name ndash A name for the site defaults to None

bull app_name ndash Defaults to lsquofilebrowserrsquo

bull storage ndash A custom storage engine defaults to Djangos default storage

Similar to djangocontribadmin you first need to add a filebrowsersite to your admin interface Inyour urlspy import the default FileBrowser site (or your custom site) and add the site to your URL-patterns (beforeany admin-urls)

from filebrowsersites import site

urlpatterns = patterns(url(r^adminurlfilebrowser include(siteurls))

)

Now you are able to browse the location defined with the storage engine associated to your site

from djangocorefilesstorage import DefaultStoragefrom filebrowsersites import FileBrowserSite

Default FileBrowser sitesite = FileBrowserSite(name=filebrowser storage=DefaultStorage())

My Custom FileBrowser sitecustom_site = FileBrowserSite(name=custom_filebrowser storage=DefaultStorage())custom_sitedirectory = custom_uploads

23

Django FileBrowser Documentation Release 357

Note The module variable site from filebrowsersites is the default FileBrowser application

412 Custom Actions

New in version 340

Similar to Djangorsquos admin actions you can define your FileBrowser actions and thus automate the typical tasks ofyour users Registered custom actions are listed in the detail view of a file and a user can select a single action at atime The selected action will then be applied to the file

The default FileBrowser image actions such as ldquoFlip Verticalrdquo or ldquoRotate 90deg Clockwiserdquo are in fact implemented ascustom actions (see the module filebrowseractions)

Writing Your Own Actions

Custom actions are simple functions

def foo(request fileobjects) Do something with the fileobjects

The first parameter is a HttpRequest object (representing the submitted form in which a user selected the action)and the second parameter is a list of FileObjects to which the action should be applied

The list contains exactly one instance of FileObject (representing the file from the detail view) but this may change inthe future as custom actions may become available also in browse views (similar to admin actions applied to a list ofchecked objects)

Registering an Action

In order to make your action visible you need to register it with a FileBrowser site

siteadd_action(foo)

Once registered the action will appear in the detail view of a file You can also give your action a short description

fooshort_description = Do foo with the File

This short description will then appear in the list of available actions If you do not provide a short description thefunction name will be used instead and FileBrowser will replace any underscores in the function name with spaces

Associating Actions with Specific Files

Each custom action can be associated with a specific file type (eg images audio file etc) to which it applies In orderto do that you need to define a predicatefilter function which takes a single argument (FileObject) and returns Trueif your action is applicable to that FileObject Finally you need to register this filter function with your action

fooapplies_to(lambda fileobject fileobjectfiletype == Image)

In the above example foo will appear in the action list only for image files If you do not specify any filter functionfor your action FileBrowser considers the action as applicable to all files

24 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

Messages amp Intermediate Pages

You can provide a feedback to a user about a successful or failed execution of an action by using a message Forexample

from djangocontrib import messages

def desaturate_image(request fileobjects)for f in fileobjects

Desaturate the imagemessagesadd_message(request messagesSUCCESS _(Image s was desaturated) ffilename)

Some actions may require user confirmation (eg in order to prevent accidental and irreversible modification tofiles) In order to that follow the same pattern as with Djangorsquos admin action and return a HttpResponse objectfrom your action Good practice for intermediate pages is to implement a confirm view and have your action returnHttpResponseRedirect

def crop_image(request fileobjects)files = ampf=join([fpath_relative for f in fileobjects])return HttpResponseRedirect(confirmaction=crop_imageampf=s files)

413 File Storages

New in version 340

You have the option to specify which file storage engine a FileBrowser should use to browseuploadmodify yourmedia files This enables you to use a FileBrowser even if your media files are located at some remote system Seealso the Djangorsquos documentation on storages httpsdocsdjangoprojectcomendevtopicsfiles

To associate a FileBrowser site with a particular storage engine set the storage property of a site object

from djangocorefilesstorage import FileSystemStoragesitestorage = FileSystemStorage(location=pathtomediadirectory base_url=media)

For storage classes other than FileSystemStorage (or those that inherit from that class) therersquos more effort involved inproviding a storage object that can be used with FileBrowser See StorageMixin Class

Note Prior FileBrowser 34 the way to specify FileBrowserlsquos MEDIA_ROOT and MEDIA_URL was via settingspyStarting from version 34 those variables are associated with the storage instance and you can set them as illustratedin the above example

Warning For the reason of backward compatibility FileBrowser settings FILEBROWSER_MEDIA_ROOT andFILEBROWSER_MEDIA_URL can still be used to customize FileBrowser as long as yoursquore using the defaultFileBrowserlsquos site without having changed its storage engine In the next major release of FileBrowser thesesettings will be removed

StorageMixin Class

A FileBrowser uses the Djangorsquos Storage class to access media files However the API of the Storageclass does not provide all methods necessary for FileBrowserrsquos functionality A StorageMixin class fromfilebrowserstorage module therefore defines all the additional methods that a FileBrowser requires

isdir(self name)Returns true if name exists and is a directory

41 Admin Interface 25

Django FileBrowser Documentation Release 357

isfile(self name)Returns true if name exists and is a regular file

move(self old_file_name new_file_name allow_overwrite=False)Moves safely a file from one location to another If allow_ovewrite==False and new_file_nameexists raises an exception

makedirs(self name)Creates all missing directories specified by name Analogue to osmkdirs()

414 Views

All views use the staff_member_requird and path_exists decorator in order to check if the server pathactually exists Some views also use the file_exists decorator

bull Browse fb_browse Browse a directory on your server Returns a FileListing

ndash Optional query string args dir o ot q p filter_date filter_type type

bull Create directory fb_createdir Create a new folder on your server

ndash Optional query string args dir

ndash Signals filebrowser_pre_createdir filebrowser_post_createdir

bull Upload fb_upload Multiple upload

ndash Optional query string args dir type

ndash Signals filebrowser_pre_upload filebrowser_post_upload

bull Edit fb_edit Edit a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_rename filebrowser_post_rename

You are able to apply custom actions (see Custom Actions) to the edit-view

bull Confirm delete fb_confirm_delete Confirm the deletion of a file or folder

ndash Required query string args filename

ndash Optional query string args dir

If you try to delete a folder all filesfolders within this folder are listed on this page

bull Delete fb_delete Delete a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_delete filebrowser_post_delete

Warning If you delete a Folder all items within this Folder are being deleted

bull Version fb_version Generate a version of an image as defined with ADMIN_VERSIONS

ndash Required query string args filename

ndash Optional Query string args dir

This is a helper used by the FileBrowseField and TinyMCE for selecting a version

26 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

415 Signals

The FileBrowser sends a couple of different signals Please take a look at the module filebrowsersignals for furtherexplanation on the provided arguments

bull filebrowser_pre_upload Sent before a an Upload starts

bull filebrowser_post_upload Sent after an Upload has finished

bull filebrowser_pre_delete Sent before an Item (File Folder) is deleted

bull filebrowser_post_delete Sent after an Item (File Folder) has been deleted

bull filebrowser_pre_createdir Sent before a new Folder is created

bull filebrowser_post_createdir Sent after a new Folder has been created

bull filebrowser_pre_rename Sent before an Item (File Folder) is renamed

bull filebrowser_post_rename Sent after an Item (File Folder) has been renamed

bull filebrowser_actions_pre_apply Sent before a custom action is applied

bull filebrowser_actions_post_apply Sent after a custom action has been applied

Example for using these Signals

Herersquos a small example for using the above Signals

from filebrowser import signals

def pre_upload_callback(sender kwargs)Receiver function called before an upload startsprint Pre Upload Callbackprint kwargs kwargs

signalsfilebrowser_pre_uploadconnect(pre_upload_callback)

def post_upload_callback(sender kwargs)Receiver function called each time an upload has finishedprint Post Upload Callbackprint kwargs kwargs You can use all attributes available with the FileObject This is just an example print Filesize kwargs[file]filesizeprint Orientation kwargs[file]orientationprint Extension kwargs[file]extension

signalsfilebrowser_post_uploadconnect(post_upload_callback)

41 Admin Interface 27

Django FileBrowser Documentation Release 357

28 Chapter 4 Admin Interface

CHAPTER 5

Image Versions

51 Versions

With the FileBrowser you are able to define different versionssizes for images This enables you to save an originalimage on your server while having different versions of that image to automatically fit your websites grid Versionsare also useful for responsiveadaptive layouts

511 Defining Versions

New in version 340 methods

First you need to know which versionssizes of an image yoursquod like to generate with your website Letrsquos say yoursquoreusing a 12 column grid with 60px for each column and 20px margin (which is a total of 940px) With this grid youcould (for example) define these image versions

FILEBROWSER_VERSIONS_BASEDIR = _versionsFILEBROWSER_VERSIONS =

admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

Use the methods argument if you need to add a filter

def grayscale(im)Convert image to grayscaleif immode = L

im = imconvert(L)return im

FILEBROWSER_VERSIONS = big verbose_name Big (6 col) width 460 height opts methods [grayscale]

)

29

Django FileBrowser Documentation Release 357

512 Versions and the Admin

When using the FileBrowser with the admin interface you need to define ADMIN_VERSIONS andADMIN_THUMBNAIL (see Settings) ADMIN_VERSIONS are available with the admin ie you are able to seethese versions with the image detail view and you are able to select the versions with the FileBrowseField model field

FILEBROWSER_ADMIN_VERSIONS = [thumbnail small medium big large]FILEBROWSER_ADMIN_THUMBNAIL = admin_thumbnail

513 Versions and the Frontend

With your templates you have two different tags to choose from version and version_object With bothtags the version will be generated if it doesnrsquot already exist OR if the original image is newer than the version Inorder to update an image you just overwrite the original image and the versions will be generated automatically (asyou request them within your template)

A Model example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 blank=True null=True)

With your templates use version if you simply need to retrieve the URL or version_object if you need to geta FileObject

lt-- load filebrowser templatetags --gt load fb_versions

lt-- get the url with version --gtltimg src= version blogentryimage medium gt

lt-- get a fileobject with version_object --gt version_object blogentryimage medium as version_medium version_mediumwidth ltimg src= version_medium gt

Templatetag version

RetrievesGenerates a version and returns an URL

version modelfield_name version_prefix

Templatetag version_object

RetrievesGenerates a version and returns a FileObject

version_object modelfield_name version_prefix as variable

Note With both templatetags version_prefix can either be a string or a variable If version_prefix is astring use quotes

30 Chapter 5 Image Versions

Django FileBrowser Documentation Release 357

514 Versions in Views

If you have a FileObject you can generateretrieve a version with

v = objimageversion_generate(version_prefix) returns a FileObject

515 Placeholder

When developing on a locale machine or a development-server you might not have all the images (resp media-files)available that are on your production instance and downloading these files on a regular basis might not be an option

In that case you can use a placeholder instead of a version You just need to define the PLACEHOLDER and overwritethe settings SHOW_PLACEHOLDER andor FORCE_PLACEHOLDER (see Placeholder)

516 Management Commands

fb_version_generateIf you need to generate certain (or all) versions type

python managepy fb_version_generate

fb_version_removeIf you need to generate certain (or all) versions type

python managepy fb_version_generate

Warning Please be very careful with this command

51 Versions 31

Django FileBrowser Documentation Release 357

32 Chapter 5 Image Versions

CHAPTER 6

Help

61 Help

611 FAQ

Why should I use the FileBrowser

If you need your editors or customers to manage files the FileBrowser is an alternative to an FTP-client Moreoveryou are able to define different image versions according to your websites grid Alternatives to the FileBrowser can befound at httpdjangopackagescomgridsgfile-managers

Do I need Grappelli

Grappelli is a requirement for using the FileBrowser There are several filebrowser-no-grappelli repositories (most ofthem on GitHub) but we donrsquot follow the development

I need help

see Troubleshooting

Why are there no fancy effects

The FileBrowser is about managing files We think that you should prepare your files before uploading them to theserver

How do I upload to another server

Use a custom storage engine see httpsdocsdjangoprojectcomen16howtocustom-file-storage

Why do I need image-versions

You need image-versions if your website is based on a grid

33

Django FileBrowser Documentation Release 357

Is the FileBrowser stable

Wersquove developed the FileBrowser for a couple of years and use it with almost all of our clients That said Grappelli isthe more stable and mature application

How can I contribute

Help is very much needed and appreciated Test the FileBrowser and submit feedbackpatches

Who develops the FileBrowser

The FileBrowser is developed and maintained by Patrick Kranzlmuumlller amp Axel Swoboda of vonautomatisch

612 Troubleshooting

Check your setup

Please check if the problem is caused by your setup

bull Read Quick start guide

bull Check if the staticmedia-files are served correctly

bull Make sure you have removed all custom FileBrowser templates from all locations in TEMPLATE_DIRS orcheck that these templates are compatible with the FileBrowser

Run the tests

Start the shell and type

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Check issues

If your setup is fine please check if your problem is a known issue

bull Take a look at all FileBrowser Issues (incuding closed) and search the FileBrowser Google-Group

Add a ticket

If you think yoursquove found a bug please add a ticket

bull Try to describe your problem as precisely as possible

bull Tell us what you did in order to solve the problem

bull Tell us what version of the FileBrowser you are using

bull Tell us what version of Django you are using

34 Chapter 6 Help

Django FileBrowser Documentation Release 357

bull Please do NOT add tickets if yoursquore having problems with serving staticmedia-files (because this is not relatedto the FileBrowser)

bull Please do NOT add tickets referring to Djangos trunk version

bull At best add a patch

Note Be aware that we may close issues not following these guidlines without further notifications

613 Translation

Translation is done via Transifex

Supported Languages

see httpswwwtransifexnetprojectspdjango-filebrowserresourcedjangopo

614 FileBrowser 35 Release Notes

FileBrowser 35 is compatible with Django 14151617 as well as Grappelli 242526

Update from FileBrowser 34x

bull Update Django to 14151617 and check httpsdocsdjangoprojectcomendevreleases14 orhttpsdocsdjangoprojectcomendevreleases15 or httpsdocsdjangoprojectcomendevreleases16

bull Update Grappelli to 24x25x26x

bull Update FileBrowser to 35x

62 Changelog

621 358 (not yet released)

622 357 (September 10th 2014)

bull New Compatibility with Django 17 and Grappelli 26x

bull Improved Updated tests because of the new random suffix with get_available_name (django storage)

bull Improved Added an icon in order to mark finished uploads

bull Improved Show resulting filename (eg with suffix converted) after successful upload

bull Fixed Permissions with file upload

bull Fixed Unified json response with _upload_file (no matter if file already exists or not)

623 356 (April 16th 2014)

bull Fixed Displaying pagination correctly with lots of entries

62 Changelog 35

Django FileBrowser Documentation Release 357

624 355 (April 13th 2014)

bull New Added client-side (JavaScript) file extension validation to the AJAX uploader

bull New Added experimental Python 33 support

bull Improved Tests with convertnormalize (removed special chars from test filename)

bull Fixed File selection after using search box (CKEditor)

bull Fixed Removed encoding of file URIs with CKEditor

625 354 (February 21st 2014)

bull Fixed Placeholder functionality (including tests)

bull Fixed Convertnormalize filenames (including tests)

bull Fixed Handling uppercase extensions with browse

626 353 (January 7 2014)

bull New added path_full to FileObject

bull Improved added docx to EXTENSIONS

bull Improved Recommend pillow instead of PIL as a requirement

bull Improved Added additional test cases

bull Improved Updated documentation

bull Improved Consistent use of storage (eg storagelocation storageurl)

bull Improved Removed unnecessary functions (eg url_join url_strip)

bull Improved Moved sort_by_attr to FileListing

bull Improved Regex matches with file versions on browse

bull Improved Using djangoconfurls (with djangoconfurlsdefaults as fallback)

bull Improved Adding CONTRIBUTINGrst

bull Improved Removed static Media inner class with fields

bull Improved Removed search icon with fields (has not being used)

bull Improved Added custom class attributes with filebrowser field

bull Improved Updated translations

bull Fixed fixed exception handling with python 25

bull Fixed fixes dir with SEARCH_TRAVERSE true and version select

bull Fixed Make Django FileUploadHandlers work (also fixed a memory leak)

bull Fixed return correct filename with OVERWRITE_EXISTING

bull Fixed fb_version_generate with FILEBROWSER_VERSIONS_BASEDIR

bull Fixed Table sorting with ascdesc

bull Fixed Added DeprecationWarning for FileObjectdirectory and FileObjectfolder

36 Chapter 6 Help

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

Django FileBrowser Documentation Release 357

113 Settings

Check the Settings

Note You need to add a folder ldquouploadsrdquo within sitestoragelocation when using the default settingsAnd we strongly recommend to define a VERSIONS_BASEDIR

114 Testing

Run the FileBrowser tests

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Start the devserver and login to your admin site

python managepy runserver ltIP-addressgt8000

Goto adminfilebrowserbrowse and check if everything looksworks as expected If yoursquore having problems seeTroubleshooting

12 Settings

There are some settings in order to customize the FileBrowser Nonetheless you should be able to start with the defaultsettings

All settings can be defined in your projects settings-file In that case you have to use the prefix FILEBROWSER_ forevery setting (eg FILEBROWSER_EXTENSIONS instead of EXTENSIONS)

121 Main URLPaths Settings

MEDIA_ROOT

Warning Will be removed with version 360 Since 34 MEDIA_ROOT is defined with your storage engine

The absolute path to the directory that holds the media-files you want to browse

MEDIA_ROOT = getattr(settings FILEBROWSER_MEDIA_ROOT settingsMEDIA_ROOT)

MEDIA_URL

Warning Will be removed with version 360 Since 34 MEDIA_URL is defined with your storage engine

URL that handles the media served from MEDIA_ROOT

MEDIA_URL = getattr(settings FILEBROWSER_MEDIA_URL settingsMEDIA_URL)

4 Chapter 1 Installation and Setup

Django FileBrowser Documentation Release 357

DIRECTORY (relative to storage location)

Main FileBrowser Directory Leave empty in order to browse all files and folders within a storage location

DIRECTORY = getattr(settings FILEBROWSER_DIRECTORY uploads)

You can override this setting on a perndashsite basis

from filebrowsersites import sitesitedirectory = uploads

122 FileBrowser Media TinyMCE Media

Deprecated since version 353 Use staticfiles instead

123 Extensions and Formats

EXTENSIONS

Allowed extensions for file upload

EXTENSIONS = getattr(settings FILEBROWSER_EXTENSIONS Folder []Image [jpgjpeggifpngtiftiff]Document [pdfdocrtftxtxlscsv]Video [movwmvmpegmpgavirm]Audio [mp3mp4wavaiffmidim4p]

)

SELECT_FORMATS

Set different Options for selecting elements from the FileBrowser

SELECT_FORMATS = getattr(settings FILEBROWSER_SELECT_FORMATS file [FolderImageDocumentVideoAudio]image [Image]document [Document]media [VideoAudio]

)

When using the browse-function for selecting FilesFolders you can use an additional query-attribute type in orderto restrict the choices

124 Versions

VERSIONS_BASEDIR (relative to storage location)

Changed in version 340

Directory to save image versions (and thumbnails) If no directory is given versions are stored at the same location asthe original image

12 Settings 5

Django FileBrowser Documentation Release 357

VERSIONS_BASEDIR = getattr(settings FILEBROWSER_VERSIONS_BASEDIR )

We do recommend the following structure for media files

-- media sitestoragelocation (eg MEDIA_ROOT)-- _versions VERSIONS_BASEDIR (outside of sitedirectory)-- uploads sitedirectory

Warning If VERSIONS_BASEDIR is within sitedirectory it will be browsed

Warning With the next major release (360) the default setting will be ldquo_versionsrdquo

VERSIONS

Define the versions according to your websites grid

VERSIONS = getattr(settings FILEBROWSER_VERSIONS admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

)

VERSION_QUALITY

Quality of saved versions

VERSION_QUALITY = getattr(settings FILEBROWSER_VERSION_QUALITY 90)

ADMIN_VERSIONS

The versions you want to show with the admin interface

ADMIN_VERSIONS = getattr(settings FILEBROWSER_ADMIN_VERSIONS [thumbnail small medium big large])

ADMIN_THUMBNAIL

The version being used as the admin thumbnail

ADMIN_THUMBNAIL = getattr(settings FILEBROWSER_ADMIN_THUMBNAIL admin_thumbnail)

125 Placeholder

With your locale environment you donrsquot necessarily have access to all media files (eg images uploaded by yourclient) Therefore you can use a PLACEHOLDER

6 Chapter 1 Installation and Setup

Django FileBrowser Documentation Release 357

PLACEHOLDER

Path to placeholder image (relative to storage location)

PLACEHOLDER = getattr(settings FILEBROWSER_PLACEHOLDER )

SHOW_PLACEHOLDER

Show placeholder (instead of a version) if the original image does not exist

SHOW_PLACEHOLDER = getattr(settings FILEBROWSER_SHOW_PLACEHOLDER False)

FORCE_PLACEHOLDER

Always show placeholder (even if the original image exists)

FORCE_PLACEHOLDER = getattr(settings FILEBROWSER_FORCE_PLACEHOLDER False)

126 Extra Settings

SAVE_FULL_URL

Deprecated since version 340 With custom storage engines saving the full URL doesnrsquot make sense anymoreMoreover removing this settings allows for easily replacing a FileBrowseField with Djangos File- or ImageField

STRICT_PIL

If set to True the FileBrowser will not try to import a mis-installed PIL

STRICT_PIL = getattr(settings FILEBROWSER_STRICT_PIL False)

IMAGE_MAXBLOCK

see httpmailpythonorgpipermailimage-sig1999-August000816html

IMAGE_MAXBLOCK = getattr(settings FILEBROWSER_IMAGE_MAXBLOCK 10241024)

EXCLUDE

Exclude-patterns for files you donrsquot want to show

EXTENSION_LIST = []for exts in EXTENSIONSvalues()

EXTENSION_LIST += extsEXCLUDE = getattr(settings FILEBROWSER_EXCLUDE (r_((exts)s)__qd13((exts)s) exts (|join(EXTENSION_LIST))))

12 Settings 7

Django FileBrowser Documentation Release 357

MAX_UPLOAD_SIZE

Max Upload Size in Bytes

MAX_UPLOAD_SIZE = getattr(settings FILEBROWSER_MAX_UPLOAD_SIZE 10485760)

NORMALIZE_FILENAME

True if you want to normalize filename on upload and remove all non-alphanumeric characters (except for under-scores spaces amp dashes)

NORMALIZE_FILENAME = getattr(settings FILEBROWSER_NORMALIZE_FILENAME False)

CONVERT_FILENAME

True if you want to convert the filename on upload (replace spaces and convert to lowercase)

CONVERT_FILENAME = getattr(settings FILEBROWSER_CONVERT_FILENAME True)

LIST_PER_PAGE

How many items appear on each paginated list

LIST_PER_PAGE = getattr(settings FILEBROWSER_LIST_PER_PAGE 50)

DEFAULT_SORTING_BY

Default sorting attribute

DEFAULT_SORTING_BY = getattr(settings FILEBROWSER_DEFAULT_SORTING_BY date)

Options are date filesize filename_lower filetype_checked

DEFAULT_SORTING_ORDER

Default sorting order

DEFAULT_SORTING_ORDER = getattr(settings FILEBROWSER_DEFAULT_SORTING_ORDER desc)

Options are asc or desc

FOLDER_REGEX

regex to clean directory names before creation

FOLDER_REGEX = getattr(settings FILEBROWSER_FOLDER_REGEX r^[w_ -]+$)

8 Chapter 1 Installation and Setup

Django FileBrowser Documentation Release 357

SEARCH_TRAVERSE

True if you want to traverse all subdirectories when searching Please note that with thousands of filesdirectoriesthis might take a while

SEARCH_TRAVERSE = getattr(settings FILEBROWSER_SEARCH_TRAVERSE False)

DEFAULT_PERMISSIONS

Default upload and version permissions

DEFAULT_PERMISSIONS = getattr(settings FILEBROWSER_DEFAULT_PERMISSIONS 0755)

OVERWRITE_EXISTING

New in version 351

True in order to overwrite existing files False to use the behaviour of the storage engine

OVERWRITE_EXISTING = getattr(settings FILEBROWSER_OVERWRITE_EXISTING True)

12 Settings 9

Django FileBrowser Documentation Release 357

10 Chapter 1 Installation and Setup

CHAPTER 2

API

21 API

211 FileListing

class FileListing(path filter_func=None sorting_by=None sorting_order=None)Returns a list of FileObjects for a server path see FileObject

Parameters

bull path ndash Relative path to a location within sitestoragelocation

bull filter_func ndash Filter function see example below

bull sorting_by ndash Sort the files by any attribute of FileObject

bull sorting_order ndash Sorting order either ldquoascrdquo or ldquodescrdquo

If you want to list all files within a storage location you do

from filebrowsersites import sitefrom filebrowserbase import FileListingfilelisting = FileListing(sitestoragelocation sorting_by=date sorting_order=desc)

Use a custom filter function to limit the list of files

def filter_filelisting(item) item is a FileObjectreturn itemfiletype = Folder

filelisting = FileListing(sitestoragelocation filter_func=filter_listing sorting_by=date sorting_order=desc)

Methods

For the below examples wersquore using this folder-structure

mediauploadstestfoldertestimagejpgmediauploadsblog1imagesblogimagejpg

Note We defined filter_browse as filter_func (see sitespy) And we did not define aVERSIONS_BASEDIR for this demonstration though it is highly recommended to use one

11

Django FileBrowser Documentation Release 357

listing()Returns all items for the given path with oslistdir(path)

gtgtgt for item in filelistinglisting() print itemblogtestfolder

walk()Returns all items for the given path with oswalk(path)

gtgtgt for item in filelistingwalk() print itemblogblog1blog1imagesblog1imagesblogimagejpgblog1imagesblogimage_admin_thumbnailjpgblog1imagesblogimage_mediumjpgblog1imagesblogimage_smalljpgblog1imagesblogimage_thumbnailjpgtestfoldertestfoldertestimagejpg

files_listing_total()Returns a sorted list of FileObjects for listing()

gtgtgt for item in filelistingfiles_listing_total() print itemuploadsbloguploadstestfolder

files_walk_total()Returns a sorted list of FileObjects for walk()

gtgtgt for item in filelistingfiles_walk_total() print itemuploadsbloguploadsblog1uploadsblog1imagesuploadsblog1imagesblogimagejpguploadsblog1imagesblogimage_admin_thumbnailjpguploadsblog1imagesblogimage_mediumjpguploadsblog1imagesblogimage_smalljpguploadsblog1imagesblogimage_thumbnailjpguploadstestfolderuploadstestfoldertestimagejpg

files_listing_filtered()Returns a sorted and filtered list of FileObjects for listing()

gtgtgt for item in filelistingfiles_listing_filtered() print itemuploadsbloguploadstestfolder

files_walk_filtered()Returns a sorted and filtered list of FileObjects for walk()

12 Chapter 2 API

Django FileBrowser Documentation Release 357

gtgtgt for item in filelistingfiles_walk_filtered() print itemuploadsbloguploadsblog1uploadsblog1imagesuploadsblog1imagesblogimagejpguploadstestfolderuploadstestfoldertestimagejpg

Note The versions are not listed (compared with files_walk_total) because of filter_func

results_listing_total()Number of total files based on files_listing_total()

gtgtgt filelistingresults_listing_total()2

results_walk_total()Number of total files based on files_walk_total()

gtgtgt filelistingresults_walk_total()10

results_listing_filtered()Number of filtered files based on files_listing_filtered()

gtgtgt filelistingresults_listing_filtered()2

results_walk_filtered()Number of filtered files based on files_walk_filtered()

gtgtgt filelistingresults_walk_filtered()6

212 FileObject

class FileObject(path site=None)An object representing a media file

Parameters

bull path ndash Relative path to a location within sitestoragelocation

bull site ndash An optional FileBrowser Site

For example

from filebrowsersites import sitefrom filebrowserbase import FileObjectfileobject = FileObject(ospathjoin(sitedirectorytestfoldertestimagejpg))version = FileObject(ospathjoin(fileobjectversions_basedir testfolder testimage_mediumjpg))

21 API 13

Django FileBrowser Documentation Release 357

Attributes

Initial Attributes

pathPath relative to a storage location (including sitedirectory)

gtgtgt fileobjectpathuploadstestfoldertestimagejpg

headThe directory name of pathname path

gtgtgt fileobjectheaduploadstestfolder

filenameName of the file (including the extension) or name of the folder

gtgtgt fileobjectfilenametestimagejpg

filename_lowerLower type of filename

filename_rootFilename without extension

gtgtgt fileobjectfilename_roottestimage

extensionFile extension including the dot With a folder the extensions is None

gtgtgt fileobjectextensionjpg

mimetypeMimetype based on httpdocspythonorglibrarymimetypeshtml

gtgtgt fileobjectmimetype(imagejpeg None)

General Attributes

filetypeType of the file as defined with EXTENSIONS

gtgtgt fileobjectfiletypeImage

filesizeFilesize in Bytes

gtgtgt fileobjectfilesize870037L

14 Chapter 2 API

Django FileBrowser Documentation Release 357

dateDate based on timemktime

gtgtgt fileobjectdate12997603470

datetimeDatetime object

gtgtgt fileobjectdatetimedatetimedatetime(2011 3 10 13 32 27)

existsTrue if the path exists False otherwise

gtgtgt fileobjectexistsTrue

Path and URL attributes

pathPath relative to a storage location (including sitedirectory)

gtgtgt fileobjectpathuploadstestfoldertestimagejpg

path_relative_directoryPath relative to sitedirectory

gtgtgt fileobjectpath_relative_directorytestfoldertestimagejpg

path_fullAbsolute server path (based on storagepath)

gtgtgt fileobjectpath_fullabsolutepathtoserverlocationtestfoldertestimagejpg

dirnameNew in version 34

The directory (not including sitedirectory)

gtgtgt fileobjectdirnametestfolder

urlURL for the filefolder (based on storageurl)

gtgtgt fileobjecturlmediauploadstestfoldertestimagejpg

Image attributes

The image attributes are only useful if the FileObject represents an image

dimensionsImage dimensions as a tuple

21 API 15

Django FileBrowser Documentation Release 357

gtgtgt fileobjectdimensions(1000 750)

widthImage width in px

gtgtgt fileobjectwidth1000

heightImage height in px

gtgtgt fileobjectheight750

aspectratioAspect ratio (float format)

gtgtgt fileobjectaspectratio133534908

orientationImage orientation either Landscape or Portrait

gtgtgt fileobjectorientationLandscape

Folder attributes

The folder attributes make sense when the FileObject represents a directory (not a file)

directory

Deprecated since version 353 Use path_relative_directory instead

folder

Deprecated since version 353 Use dirname instead

is_folderTrue if path is a folder

gtgtgt fileobjectis_folderFalse

is_emptyTrue if the folder is empty False if the folder is not empty or the FileObject is not a folder

gtgtgt fileobjectis_emptyFalse

Version attributes

is_versiontrue if the File is a version of another File

16 Chapter 2 API

Django FileBrowser Documentation Release 357

gtgtgt fileobjectis_versionFalsegtgtgt versionis_versionTrue

versions_basedirThe relative path (from storage location) to the main versions folder Either VERSIONS_BASEDIR orsitedirectory

gtgtgt fileobjectversions_basedir_versionsgtgtgt versionversions_basedir_versions

originalReturns the original FileObject

gtgtgt fileobjectoriginalltFileObject uploadstestfoldertestimagejpggtgtgtgt versionoriginalltFileObject uploadstestfoldertestimagejpggt

original_filenameGet the filename of an original image from a version

gtgtgt fileobjectoriginal_filenametestimagejpggtgtgt versionoriginal_filenametestimagejpg

Methods

Version methods

versions()List all filenames based on VERSIONS

gtgtgt fileobjectversions()[_versionstestfoldertestimage_admin_thumbnailjpg_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionversions()[]

Note The versions are not being generated

admin_versions()List all filenames based on ADMIN_VERSIONS

gtgtgt fileobjectadmin_versions()[_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg

21 API 17

Django FileBrowser Documentation Release 357

_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionadmin_versions()[]

Note The versions are not being generated

version_name(version_suffix)Get the filename for a version

gtgtgt fileobjectversion_name(medium)testimage_mediumjpg

Note The version is not being generated

version_path(version_suffix)Get the path for a version

gtgtgt fileobjectversion_path(medium)_versionstestfoldertestimage_mediumjpg

Note The version is not being generated

version_generate(version_suffix)Generate a version

gtgtgt fileobjectversion_generate(medium)ltFileObject uploadstestfoldertestimage_mediumjpggt

Please note that a version is only generated if it does not already exist or if the original image is newer than theexisting version

Delete methods

delete()Delete the File or Folder from the server

Warning If you delete a Folder all items within the folder are being deleted

delete_versions()Delete all VERSIONS

delete_admin_versions()Delete all ADMIN_VERSIONS

18 Chapter 2 API

CHAPTER 3

Fields amp Widgets

31 Fields amp Widgets

The FileBrowseField is a custom model field which returns a FileObject The widgets FileInput and ClearableFileIn-put are used with the admin app in order to show an additional thumbnail for images

311 FileBrowseField

class FileBrowseField(max_length[ site directory extensions format options])A subclass of CharField referencing a media file within Returns a FileObject

Parameters

bull site ndash A FileBrowser site (defaults to the main site) see FileBrowser Site

bull directory ndash Directory to browse when clicking the search icon

bull extensions ndash List of allowed extensions see Extensions and Formats

bull format ndash A key from SELECT_FORMATS in order to restrict the selection to specificfiletypes see Extensions and Formats

For example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 directory=images extensions=[jpg] blank=True null=True)document = FileBrowseField(PDF max_length=200 directory=documents extensions=[pdfdoc] blank=True null=True)

FileBrowseField in Templates

You can use all attributes from FileObject

blogentryimage ltimg src= publicationimageurl gt

ifequal blogentryimageimage_orientation landscape ltimg src= blogentryimageurl class=landscape gt

endifequal

19

Django FileBrowser Documentation Release 357

Showing Thumbnail in the Changelist

To show a thumbnail with the changelist you can define a ModelAdmin method

from filebrowsersettings import ADMIN_THUMBNAIL

def image_thumbnail(self obj)if objimage and objimagefiletype == Image

return ltimg src=s gt objimageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Using the FileBrowseField with TinyMCE

In order to replace the TinyMCE imagefile manager with the FileBrowser you have to use a FileBrowser CallbackTherersquos an example TinyMCE configuration file in staticjs called TinyMCEAdminjs You can either copy theFileBrowserCallback to your own file or just use tinymce_setupjs (which comes with django-grappelli)

Just add these lines to your ModelAdmin asset definitions

class Mediajs = [pathtotinymcejscriptstiny_mcetiny_mcejs

pathtoyourtinymce_setupjs]

312 FileInput

Subclass of FileInput with an additional thumbnail

from filebrowserwidgets import FileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget FileInput

313 ClearableFileInput

Subclass of ClearableFileInput with an additional thumbnail

from filebrowserwidgets import ClearableFileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget ClearableFileInput

314 Django FileField and the FileBrowser

Return a FileObject from a FileField or ImageField with

20 Chapter 3 Fields amp Widgets

Django FileBrowser Documentation Release 357

from filebrowserbase import FileObject

image_upload = modelsImageField(uImage (Upload) max_length=250 upload_to=image_upload_path blank=True null=True)

def image(self)if selfimage_upload

return FileObject(selfimage_uploadpath)return None

In order show a thumbnail with your changelist you could use a ModelAdmin method

from filebrowserbase import FileObject

def image_thumbnail(self obj)if objimage_upload

image = FileObject(objimage_uploadpath)if imagefiletype == Image

return ltimg src=s gt imageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Note There are different ways to achieve this The above examples show one of several options

31 Fields amp Widgets 21

Django FileBrowser Documentation Release 357

22 Chapter 3 Fields amp Widgets

CHAPTER 4

Admin Interface

41 Admin Interface

The main FileBrowser admin application is an extension for the Django admin interface in order to browser yourmedia folder upload and renamedelete files

411 FileBrowser Site

New in version 340

class FileBrowserSite(name=None app_name=rsquofilebrowserrsquo storage=default_storage)Respresents the FileBrowser admin application (similar to Djangorsquos admin site)

Parameters

bull name ndash A name for the site defaults to None

bull app_name ndash Defaults to lsquofilebrowserrsquo

bull storage ndash A custom storage engine defaults to Djangos default storage

Similar to djangocontribadmin you first need to add a filebrowsersite to your admin interface Inyour urlspy import the default FileBrowser site (or your custom site) and add the site to your URL-patterns (beforeany admin-urls)

from filebrowsersites import site

urlpatterns = patterns(url(r^adminurlfilebrowser include(siteurls))

)

Now you are able to browse the location defined with the storage engine associated to your site

from djangocorefilesstorage import DefaultStoragefrom filebrowsersites import FileBrowserSite

Default FileBrowser sitesite = FileBrowserSite(name=filebrowser storage=DefaultStorage())

My Custom FileBrowser sitecustom_site = FileBrowserSite(name=custom_filebrowser storage=DefaultStorage())custom_sitedirectory = custom_uploads

23

Django FileBrowser Documentation Release 357

Note The module variable site from filebrowsersites is the default FileBrowser application

412 Custom Actions

New in version 340

Similar to Djangorsquos admin actions you can define your FileBrowser actions and thus automate the typical tasks ofyour users Registered custom actions are listed in the detail view of a file and a user can select a single action at atime The selected action will then be applied to the file

The default FileBrowser image actions such as ldquoFlip Verticalrdquo or ldquoRotate 90deg Clockwiserdquo are in fact implemented ascustom actions (see the module filebrowseractions)

Writing Your Own Actions

Custom actions are simple functions

def foo(request fileobjects) Do something with the fileobjects

The first parameter is a HttpRequest object (representing the submitted form in which a user selected the action)and the second parameter is a list of FileObjects to which the action should be applied

The list contains exactly one instance of FileObject (representing the file from the detail view) but this may change inthe future as custom actions may become available also in browse views (similar to admin actions applied to a list ofchecked objects)

Registering an Action

In order to make your action visible you need to register it with a FileBrowser site

siteadd_action(foo)

Once registered the action will appear in the detail view of a file You can also give your action a short description

fooshort_description = Do foo with the File

This short description will then appear in the list of available actions If you do not provide a short description thefunction name will be used instead and FileBrowser will replace any underscores in the function name with spaces

Associating Actions with Specific Files

Each custom action can be associated with a specific file type (eg images audio file etc) to which it applies In orderto do that you need to define a predicatefilter function which takes a single argument (FileObject) and returns Trueif your action is applicable to that FileObject Finally you need to register this filter function with your action

fooapplies_to(lambda fileobject fileobjectfiletype == Image)

In the above example foo will appear in the action list only for image files If you do not specify any filter functionfor your action FileBrowser considers the action as applicable to all files

24 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

Messages amp Intermediate Pages

You can provide a feedback to a user about a successful or failed execution of an action by using a message Forexample

from djangocontrib import messages

def desaturate_image(request fileobjects)for f in fileobjects

Desaturate the imagemessagesadd_message(request messagesSUCCESS _(Image s was desaturated) ffilename)

Some actions may require user confirmation (eg in order to prevent accidental and irreversible modification tofiles) In order to that follow the same pattern as with Djangorsquos admin action and return a HttpResponse objectfrom your action Good practice for intermediate pages is to implement a confirm view and have your action returnHttpResponseRedirect

def crop_image(request fileobjects)files = ampf=join([fpath_relative for f in fileobjects])return HttpResponseRedirect(confirmaction=crop_imageampf=s files)

413 File Storages

New in version 340

You have the option to specify which file storage engine a FileBrowser should use to browseuploadmodify yourmedia files This enables you to use a FileBrowser even if your media files are located at some remote system Seealso the Djangorsquos documentation on storages httpsdocsdjangoprojectcomendevtopicsfiles

To associate a FileBrowser site with a particular storage engine set the storage property of a site object

from djangocorefilesstorage import FileSystemStoragesitestorage = FileSystemStorage(location=pathtomediadirectory base_url=media)

For storage classes other than FileSystemStorage (or those that inherit from that class) therersquos more effort involved inproviding a storage object that can be used with FileBrowser See StorageMixin Class

Note Prior FileBrowser 34 the way to specify FileBrowserlsquos MEDIA_ROOT and MEDIA_URL was via settingspyStarting from version 34 those variables are associated with the storage instance and you can set them as illustratedin the above example

Warning For the reason of backward compatibility FileBrowser settings FILEBROWSER_MEDIA_ROOT andFILEBROWSER_MEDIA_URL can still be used to customize FileBrowser as long as yoursquore using the defaultFileBrowserlsquos site without having changed its storage engine In the next major release of FileBrowser thesesettings will be removed

StorageMixin Class

A FileBrowser uses the Djangorsquos Storage class to access media files However the API of the Storageclass does not provide all methods necessary for FileBrowserrsquos functionality A StorageMixin class fromfilebrowserstorage module therefore defines all the additional methods that a FileBrowser requires

isdir(self name)Returns true if name exists and is a directory

41 Admin Interface 25

Django FileBrowser Documentation Release 357

isfile(self name)Returns true if name exists and is a regular file

move(self old_file_name new_file_name allow_overwrite=False)Moves safely a file from one location to another If allow_ovewrite==False and new_file_nameexists raises an exception

makedirs(self name)Creates all missing directories specified by name Analogue to osmkdirs()

414 Views

All views use the staff_member_requird and path_exists decorator in order to check if the server pathactually exists Some views also use the file_exists decorator

bull Browse fb_browse Browse a directory on your server Returns a FileListing

ndash Optional query string args dir o ot q p filter_date filter_type type

bull Create directory fb_createdir Create a new folder on your server

ndash Optional query string args dir

ndash Signals filebrowser_pre_createdir filebrowser_post_createdir

bull Upload fb_upload Multiple upload

ndash Optional query string args dir type

ndash Signals filebrowser_pre_upload filebrowser_post_upload

bull Edit fb_edit Edit a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_rename filebrowser_post_rename

You are able to apply custom actions (see Custom Actions) to the edit-view

bull Confirm delete fb_confirm_delete Confirm the deletion of a file or folder

ndash Required query string args filename

ndash Optional query string args dir

If you try to delete a folder all filesfolders within this folder are listed on this page

bull Delete fb_delete Delete a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_delete filebrowser_post_delete

Warning If you delete a Folder all items within this Folder are being deleted

bull Version fb_version Generate a version of an image as defined with ADMIN_VERSIONS

ndash Required query string args filename

ndash Optional Query string args dir

This is a helper used by the FileBrowseField and TinyMCE for selecting a version

26 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

415 Signals

The FileBrowser sends a couple of different signals Please take a look at the module filebrowsersignals for furtherexplanation on the provided arguments

bull filebrowser_pre_upload Sent before a an Upload starts

bull filebrowser_post_upload Sent after an Upload has finished

bull filebrowser_pre_delete Sent before an Item (File Folder) is deleted

bull filebrowser_post_delete Sent after an Item (File Folder) has been deleted

bull filebrowser_pre_createdir Sent before a new Folder is created

bull filebrowser_post_createdir Sent after a new Folder has been created

bull filebrowser_pre_rename Sent before an Item (File Folder) is renamed

bull filebrowser_post_rename Sent after an Item (File Folder) has been renamed

bull filebrowser_actions_pre_apply Sent before a custom action is applied

bull filebrowser_actions_post_apply Sent after a custom action has been applied

Example for using these Signals

Herersquos a small example for using the above Signals

from filebrowser import signals

def pre_upload_callback(sender kwargs)Receiver function called before an upload startsprint Pre Upload Callbackprint kwargs kwargs

signalsfilebrowser_pre_uploadconnect(pre_upload_callback)

def post_upload_callback(sender kwargs)Receiver function called each time an upload has finishedprint Post Upload Callbackprint kwargs kwargs You can use all attributes available with the FileObject This is just an example print Filesize kwargs[file]filesizeprint Orientation kwargs[file]orientationprint Extension kwargs[file]extension

signalsfilebrowser_post_uploadconnect(post_upload_callback)

41 Admin Interface 27

Django FileBrowser Documentation Release 357

28 Chapter 4 Admin Interface

CHAPTER 5

Image Versions

51 Versions

With the FileBrowser you are able to define different versionssizes for images This enables you to save an originalimage on your server while having different versions of that image to automatically fit your websites grid Versionsare also useful for responsiveadaptive layouts

511 Defining Versions

New in version 340 methods

First you need to know which versionssizes of an image yoursquod like to generate with your website Letrsquos say yoursquoreusing a 12 column grid with 60px for each column and 20px margin (which is a total of 940px) With this grid youcould (for example) define these image versions

FILEBROWSER_VERSIONS_BASEDIR = _versionsFILEBROWSER_VERSIONS =

admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

Use the methods argument if you need to add a filter

def grayscale(im)Convert image to grayscaleif immode = L

im = imconvert(L)return im

FILEBROWSER_VERSIONS = big verbose_name Big (6 col) width 460 height opts methods [grayscale]

)

29

Django FileBrowser Documentation Release 357

512 Versions and the Admin

When using the FileBrowser with the admin interface you need to define ADMIN_VERSIONS andADMIN_THUMBNAIL (see Settings) ADMIN_VERSIONS are available with the admin ie you are able to seethese versions with the image detail view and you are able to select the versions with the FileBrowseField model field

FILEBROWSER_ADMIN_VERSIONS = [thumbnail small medium big large]FILEBROWSER_ADMIN_THUMBNAIL = admin_thumbnail

513 Versions and the Frontend

With your templates you have two different tags to choose from version and version_object With bothtags the version will be generated if it doesnrsquot already exist OR if the original image is newer than the version Inorder to update an image you just overwrite the original image and the versions will be generated automatically (asyou request them within your template)

A Model example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 blank=True null=True)

With your templates use version if you simply need to retrieve the URL or version_object if you need to geta FileObject

lt-- load filebrowser templatetags --gt load fb_versions

lt-- get the url with version --gtltimg src= version blogentryimage medium gt

lt-- get a fileobject with version_object --gt version_object blogentryimage medium as version_medium version_mediumwidth ltimg src= version_medium gt

Templatetag version

RetrievesGenerates a version and returns an URL

version modelfield_name version_prefix

Templatetag version_object

RetrievesGenerates a version and returns a FileObject

version_object modelfield_name version_prefix as variable

Note With both templatetags version_prefix can either be a string or a variable If version_prefix is astring use quotes

30 Chapter 5 Image Versions

Django FileBrowser Documentation Release 357

514 Versions in Views

If you have a FileObject you can generateretrieve a version with

v = objimageversion_generate(version_prefix) returns a FileObject

515 Placeholder

When developing on a locale machine or a development-server you might not have all the images (resp media-files)available that are on your production instance and downloading these files on a regular basis might not be an option

In that case you can use a placeholder instead of a version You just need to define the PLACEHOLDER and overwritethe settings SHOW_PLACEHOLDER andor FORCE_PLACEHOLDER (see Placeholder)

516 Management Commands

fb_version_generateIf you need to generate certain (or all) versions type

python managepy fb_version_generate

fb_version_removeIf you need to generate certain (or all) versions type

python managepy fb_version_generate

Warning Please be very careful with this command

51 Versions 31

Django FileBrowser Documentation Release 357

32 Chapter 5 Image Versions

CHAPTER 6

Help

61 Help

611 FAQ

Why should I use the FileBrowser

If you need your editors or customers to manage files the FileBrowser is an alternative to an FTP-client Moreoveryou are able to define different image versions according to your websites grid Alternatives to the FileBrowser can befound at httpdjangopackagescomgridsgfile-managers

Do I need Grappelli

Grappelli is a requirement for using the FileBrowser There are several filebrowser-no-grappelli repositories (most ofthem on GitHub) but we donrsquot follow the development

I need help

see Troubleshooting

Why are there no fancy effects

The FileBrowser is about managing files We think that you should prepare your files before uploading them to theserver

How do I upload to another server

Use a custom storage engine see httpsdocsdjangoprojectcomen16howtocustom-file-storage

Why do I need image-versions

You need image-versions if your website is based on a grid

33

Django FileBrowser Documentation Release 357

Is the FileBrowser stable

Wersquove developed the FileBrowser for a couple of years and use it with almost all of our clients That said Grappelli isthe more stable and mature application

How can I contribute

Help is very much needed and appreciated Test the FileBrowser and submit feedbackpatches

Who develops the FileBrowser

The FileBrowser is developed and maintained by Patrick Kranzlmuumlller amp Axel Swoboda of vonautomatisch

612 Troubleshooting

Check your setup

Please check if the problem is caused by your setup

bull Read Quick start guide

bull Check if the staticmedia-files are served correctly

bull Make sure you have removed all custom FileBrowser templates from all locations in TEMPLATE_DIRS orcheck that these templates are compatible with the FileBrowser

Run the tests

Start the shell and type

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Check issues

If your setup is fine please check if your problem is a known issue

bull Take a look at all FileBrowser Issues (incuding closed) and search the FileBrowser Google-Group

Add a ticket

If you think yoursquove found a bug please add a ticket

bull Try to describe your problem as precisely as possible

bull Tell us what you did in order to solve the problem

bull Tell us what version of the FileBrowser you are using

bull Tell us what version of Django you are using

34 Chapter 6 Help

Django FileBrowser Documentation Release 357

bull Please do NOT add tickets if yoursquore having problems with serving staticmedia-files (because this is not relatedto the FileBrowser)

bull Please do NOT add tickets referring to Djangos trunk version

bull At best add a patch

Note Be aware that we may close issues not following these guidlines without further notifications

613 Translation

Translation is done via Transifex

Supported Languages

see httpswwwtransifexnetprojectspdjango-filebrowserresourcedjangopo

614 FileBrowser 35 Release Notes

FileBrowser 35 is compatible with Django 14151617 as well as Grappelli 242526

Update from FileBrowser 34x

bull Update Django to 14151617 and check httpsdocsdjangoprojectcomendevreleases14 orhttpsdocsdjangoprojectcomendevreleases15 or httpsdocsdjangoprojectcomendevreleases16

bull Update Grappelli to 24x25x26x

bull Update FileBrowser to 35x

62 Changelog

621 358 (not yet released)

622 357 (September 10th 2014)

bull New Compatibility with Django 17 and Grappelli 26x

bull Improved Updated tests because of the new random suffix with get_available_name (django storage)

bull Improved Added an icon in order to mark finished uploads

bull Improved Show resulting filename (eg with suffix converted) after successful upload

bull Fixed Permissions with file upload

bull Fixed Unified json response with _upload_file (no matter if file already exists or not)

623 356 (April 16th 2014)

bull Fixed Displaying pagination correctly with lots of entries

62 Changelog 35

Django FileBrowser Documentation Release 357

624 355 (April 13th 2014)

bull New Added client-side (JavaScript) file extension validation to the AJAX uploader

bull New Added experimental Python 33 support

bull Improved Tests with convertnormalize (removed special chars from test filename)

bull Fixed File selection after using search box (CKEditor)

bull Fixed Removed encoding of file URIs with CKEditor

625 354 (February 21st 2014)

bull Fixed Placeholder functionality (including tests)

bull Fixed Convertnormalize filenames (including tests)

bull Fixed Handling uppercase extensions with browse

626 353 (January 7 2014)

bull New added path_full to FileObject

bull Improved added docx to EXTENSIONS

bull Improved Recommend pillow instead of PIL as a requirement

bull Improved Added additional test cases

bull Improved Updated documentation

bull Improved Consistent use of storage (eg storagelocation storageurl)

bull Improved Removed unnecessary functions (eg url_join url_strip)

bull Improved Moved sort_by_attr to FileListing

bull Improved Regex matches with file versions on browse

bull Improved Using djangoconfurls (with djangoconfurlsdefaults as fallback)

bull Improved Adding CONTRIBUTINGrst

bull Improved Removed static Media inner class with fields

bull Improved Removed search icon with fields (has not being used)

bull Improved Added custom class attributes with filebrowser field

bull Improved Updated translations

bull Fixed fixed exception handling with python 25

bull Fixed fixes dir with SEARCH_TRAVERSE true and version select

bull Fixed Make Django FileUploadHandlers work (also fixed a memory leak)

bull Fixed return correct filename with OVERWRITE_EXISTING

bull Fixed fb_version_generate with FILEBROWSER_VERSIONS_BASEDIR

bull Fixed Table sorting with ascdesc

bull Fixed Added DeprecationWarning for FileObjectdirectory and FileObjectfolder

36 Chapter 6 Help

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

Django FileBrowser Documentation Release 357

DIRECTORY (relative to storage location)

Main FileBrowser Directory Leave empty in order to browse all files and folders within a storage location

DIRECTORY = getattr(settings FILEBROWSER_DIRECTORY uploads)

You can override this setting on a perndashsite basis

from filebrowsersites import sitesitedirectory = uploads

122 FileBrowser Media TinyMCE Media

Deprecated since version 353 Use staticfiles instead

123 Extensions and Formats

EXTENSIONS

Allowed extensions for file upload

EXTENSIONS = getattr(settings FILEBROWSER_EXTENSIONS Folder []Image [jpgjpeggifpngtiftiff]Document [pdfdocrtftxtxlscsv]Video [movwmvmpegmpgavirm]Audio [mp3mp4wavaiffmidim4p]

)

SELECT_FORMATS

Set different Options for selecting elements from the FileBrowser

SELECT_FORMATS = getattr(settings FILEBROWSER_SELECT_FORMATS file [FolderImageDocumentVideoAudio]image [Image]document [Document]media [VideoAudio]

)

When using the browse-function for selecting FilesFolders you can use an additional query-attribute type in orderto restrict the choices

124 Versions

VERSIONS_BASEDIR (relative to storage location)

Changed in version 340

Directory to save image versions (and thumbnails) If no directory is given versions are stored at the same location asthe original image

12 Settings 5

Django FileBrowser Documentation Release 357

VERSIONS_BASEDIR = getattr(settings FILEBROWSER_VERSIONS_BASEDIR )

We do recommend the following structure for media files

-- media sitestoragelocation (eg MEDIA_ROOT)-- _versions VERSIONS_BASEDIR (outside of sitedirectory)-- uploads sitedirectory

Warning If VERSIONS_BASEDIR is within sitedirectory it will be browsed

Warning With the next major release (360) the default setting will be ldquo_versionsrdquo

VERSIONS

Define the versions according to your websites grid

VERSIONS = getattr(settings FILEBROWSER_VERSIONS admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

)

VERSION_QUALITY

Quality of saved versions

VERSION_QUALITY = getattr(settings FILEBROWSER_VERSION_QUALITY 90)

ADMIN_VERSIONS

The versions you want to show with the admin interface

ADMIN_VERSIONS = getattr(settings FILEBROWSER_ADMIN_VERSIONS [thumbnail small medium big large])

ADMIN_THUMBNAIL

The version being used as the admin thumbnail

ADMIN_THUMBNAIL = getattr(settings FILEBROWSER_ADMIN_THUMBNAIL admin_thumbnail)

125 Placeholder

With your locale environment you donrsquot necessarily have access to all media files (eg images uploaded by yourclient) Therefore you can use a PLACEHOLDER

6 Chapter 1 Installation and Setup

Django FileBrowser Documentation Release 357

PLACEHOLDER

Path to placeholder image (relative to storage location)

PLACEHOLDER = getattr(settings FILEBROWSER_PLACEHOLDER )

SHOW_PLACEHOLDER

Show placeholder (instead of a version) if the original image does not exist

SHOW_PLACEHOLDER = getattr(settings FILEBROWSER_SHOW_PLACEHOLDER False)

FORCE_PLACEHOLDER

Always show placeholder (even if the original image exists)

FORCE_PLACEHOLDER = getattr(settings FILEBROWSER_FORCE_PLACEHOLDER False)

126 Extra Settings

SAVE_FULL_URL

Deprecated since version 340 With custom storage engines saving the full URL doesnrsquot make sense anymoreMoreover removing this settings allows for easily replacing a FileBrowseField with Djangos File- or ImageField

STRICT_PIL

If set to True the FileBrowser will not try to import a mis-installed PIL

STRICT_PIL = getattr(settings FILEBROWSER_STRICT_PIL False)

IMAGE_MAXBLOCK

see httpmailpythonorgpipermailimage-sig1999-August000816html

IMAGE_MAXBLOCK = getattr(settings FILEBROWSER_IMAGE_MAXBLOCK 10241024)

EXCLUDE

Exclude-patterns for files you donrsquot want to show

EXTENSION_LIST = []for exts in EXTENSIONSvalues()

EXTENSION_LIST += extsEXCLUDE = getattr(settings FILEBROWSER_EXCLUDE (r_((exts)s)__qd13((exts)s) exts (|join(EXTENSION_LIST))))

12 Settings 7

Django FileBrowser Documentation Release 357

MAX_UPLOAD_SIZE

Max Upload Size in Bytes

MAX_UPLOAD_SIZE = getattr(settings FILEBROWSER_MAX_UPLOAD_SIZE 10485760)

NORMALIZE_FILENAME

True if you want to normalize filename on upload and remove all non-alphanumeric characters (except for under-scores spaces amp dashes)

NORMALIZE_FILENAME = getattr(settings FILEBROWSER_NORMALIZE_FILENAME False)

CONVERT_FILENAME

True if you want to convert the filename on upload (replace spaces and convert to lowercase)

CONVERT_FILENAME = getattr(settings FILEBROWSER_CONVERT_FILENAME True)

LIST_PER_PAGE

How many items appear on each paginated list

LIST_PER_PAGE = getattr(settings FILEBROWSER_LIST_PER_PAGE 50)

DEFAULT_SORTING_BY

Default sorting attribute

DEFAULT_SORTING_BY = getattr(settings FILEBROWSER_DEFAULT_SORTING_BY date)

Options are date filesize filename_lower filetype_checked

DEFAULT_SORTING_ORDER

Default sorting order

DEFAULT_SORTING_ORDER = getattr(settings FILEBROWSER_DEFAULT_SORTING_ORDER desc)

Options are asc or desc

FOLDER_REGEX

regex to clean directory names before creation

FOLDER_REGEX = getattr(settings FILEBROWSER_FOLDER_REGEX r^[w_ -]+$)

8 Chapter 1 Installation and Setup

Django FileBrowser Documentation Release 357

SEARCH_TRAVERSE

True if you want to traverse all subdirectories when searching Please note that with thousands of filesdirectoriesthis might take a while

SEARCH_TRAVERSE = getattr(settings FILEBROWSER_SEARCH_TRAVERSE False)

DEFAULT_PERMISSIONS

Default upload and version permissions

DEFAULT_PERMISSIONS = getattr(settings FILEBROWSER_DEFAULT_PERMISSIONS 0755)

OVERWRITE_EXISTING

New in version 351

True in order to overwrite existing files False to use the behaviour of the storage engine

OVERWRITE_EXISTING = getattr(settings FILEBROWSER_OVERWRITE_EXISTING True)

12 Settings 9

Django FileBrowser Documentation Release 357

10 Chapter 1 Installation and Setup

CHAPTER 2

API

21 API

211 FileListing

class FileListing(path filter_func=None sorting_by=None sorting_order=None)Returns a list of FileObjects for a server path see FileObject

Parameters

bull path ndash Relative path to a location within sitestoragelocation

bull filter_func ndash Filter function see example below

bull sorting_by ndash Sort the files by any attribute of FileObject

bull sorting_order ndash Sorting order either ldquoascrdquo or ldquodescrdquo

If you want to list all files within a storage location you do

from filebrowsersites import sitefrom filebrowserbase import FileListingfilelisting = FileListing(sitestoragelocation sorting_by=date sorting_order=desc)

Use a custom filter function to limit the list of files

def filter_filelisting(item) item is a FileObjectreturn itemfiletype = Folder

filelisting = FileListing(sitestoragelocation filter_func=filter_listing sorting_by=date sorting_order=desc)

Methods

For the below examples wersquore using this folder-structure

mediauploadstestfoldertestimagejpgmediauploadsblog1imagesblogimagejpg

Note We defined filter_browse as filter_func (see sitespy) And we did not define aVERSIONS_BASEDIR for this demonstration though it is highly recommended to use one

11

Django FileBrowser Documentation Release 357

listing()Returns all items for the given path with oslistdir(path)

gtgtgt for item in filelistinglisting() print itemblogtestfolder

walk()Returns all items for the given path with oswalk(path)

gtgtgt for item in filelistingwalk() print itemblogblog1blog1imagesblog1imagesblogimagejpgblog1imagesblogimage_admin_thumbnailjpgblog1imagesblogimage_mediumjpgblog1imagesblogimage_smalljpgblog1imagesblogimage_thumbnailjpgtestfoldertestfoldertestimagejpg

files_listing_total()Returns a sorted list of FileObjects for listing()

gtgtgt for item in filelistingfiles_listing_total() print itemuploadsbloguploadstestfolder

files_walk_total()Returns a sorted list of FileObjects for walk()

gtgtgt for item in filelistingfiles_walk_total() print itemuploadsbloguploadsblog1uploadsblog1imagesuploadsblog1imagesblogimagejpguploadsblog1imagesblogimage_admin_thumbnailjpguploadsblog1imagesblogimage_mediumjpguploadsblog1imagesblogimage_smalljpguploadsblog1imagesblogimage_thumbnailjpguploadstestfolderuploadstestfoldertestimagejpg

files_listing_filtered()Returns a sorted and filtered list of FileObjects for listing()

gtgtgt for item in filelistingfiles_listing_filtered() print itemuploadsbloguploadstestfolder

files_walk_filtered()Returns a sorted and filtered list of FileObjects for walk()

12 Chapter 2 API

Django FileBrowser Documentation Release 357

gtgtgt for item in filelistingfiles_walk_filtered() print itemuploadsbloguploadsblog1uploadsblog1imagesuploadsblog1imagesblogimagejpguploadstestfolderuploadstestfoldertestimagejpg

Note The versions are not listed (compared with files_walk_total) because of filter_func

results_listing_total()Number of total files based on files_listing_total()

gtgtgt filelistingresults_listing_total()2

results_walk_total()Number of total files based on files_walk_total()

gtgtgt filelistingresults_walk_total()10

results_listing_filtered()Number of filtered files based on files_listing_filtered()

gtgtgt filelistingresults_listing_filtered()2

results_walk_filtered()Number of filtered files based on files_walk_filtered()

gtgtgt filelistingresults_walk_filtered()6

212 FileObject

class FileObject(path site=None)An object representing a media file

Parameters

bull path ndash Relative path to a location within sitestoragelocation

bull site ndash An optional FileBrowser Site

For example

from filebrowsersites import sitefrom filebrowserbase import FileObjectfileobject = FileObject(ospathjoin(sitedirectorytestfoldertestimagejpg))version = FileObject(ospathjoin(fileobjectversions_basedir testfolder testimage_mediumjpg))

21 API 13

Django FileBrowser Documentation Release 357

Attributes

Initial Attributes

pathPath relative to a storage location (including sitedirectory)

gtgtgt fileobjectpathuploadstestfoldertestimagejpg

headThe directory name of pathname path

gtgtgt fileobjectheaduploadstestfolder

filenameName of the file (including the extension) or name of the folder

gtgtgt fileobjectfilenametestimagejpg

filename_lowerLower type of filename

filename_rootFilename without extension

gtgtgt fileobjectfilename_roottestimage

extensionFile extension including the dot With a folder the extensions is None

gtgtgt fileobjectextensionjpg

mimetypeMimetype based on httpdocspythonorglibrarymimetypeshtml

gtgtgt fileobjectmimetype(imagejpeg None)

General Attributes

filetypeType of the file as defined with EXTENSIONS

gtgtgt fileobjectfiletypeImage

filesizeFilesize in Bytes

gtgtgt fileobjectfilesize870037L

14 Chapter 2 API

Django FileBrowser Documentation Release 357

dateDate based on timemktime

gtgtgt fileobjectdate12997603470

datetimeDatetime object

gtgtgt fileobjectdatetimedatetimedatetime(2011 3 10 13 32 27)

existsTrue if the path exists False otherwise

gtgtgt fileobjectexistsTrue

Path and URL attributes

pathPath relative to a storage location (including sitedirectory)

gtgtgt fileobjectpathuploadstestfoldertestimagejpg

path_relative_directoryPath relative to sitedirectory

gtgtgt fileobjectpath_relative_directorytestfoldertestimagejpg

path_fullAbsolute server path (based on storagepath)

gtgtgt fileobjectpath_fullabsolutepathtoserverlocationtestfoldertestimagejpg

dirnameNew in version 34

The directory (not including sitedirectory)

gtgtgt fileobjectdirnametestfolder

urlURL for the filefolder (based on storageurl)

gtgtgt fileobjecturlmediauploadstestfoldertestimagejpg

Image attributes

The image attributes are only useful if the FileObject represents an image

dimensionsImage dimensions as a tuple

21 API 15

Django FileBrowser Documentation Release 357

gtgtgt fileobjectdimensions(1000 750)

widthImage width in px

gtgtgt fileobjectwidth1000

heightImage height in px

gtgtgt fileobjectheight750

aspectratioAspect ratio (float format)

gtgtgt fileobjectaspectratio133534908

orientationImage orientation either Landscape or Portrait

gtgtgt fileobjectorientationLandscape

Folder attributes

The folder attributes make sense when the FileObject represents a directory (not a file)

directory

Deprecated since version 353 Use path_relative_directory instead

folder

Deprecated since version 353 Use dirname instead

is_folderTrue if path is a folder

gtgtgt fileobjectis_folderFalse

is_emptyTrue if the folder is empty False if the folder is not empty or the FileObject is not a folder

gtgtgt fileobjectis_emptyFalse

Version attributes

is_versiontrue if the File is a version of another File

16 Chapter 2 API

Django FileBrowser Documentation Release 357

gtgtgt fileobjectis_versionFalsegtgtgt versionis_versionTrue

versions_basedirThe relative path (from storage location) to the main versions folder Either VERSIONS_BASEDIR orsitedirectory

gtgtgt fileobjectversions_basedir_versionsgtgtgt versionversions_basedir_versions

originalReturns the original FileObject

gtgtgt fileobjectoriginalltFileObject uploadstestfoldertestimagejpggtgtgtgt versionoriginalltFileObject uploadstestfoldertestimagejpggt

original_filenameGet the filename of an original image from a version

gtgtgt fileobjectoriginal_filenametestimagejpggtgtgt versionoriginal_filenametestimagejpg

Methods

Version methods

versions()List all filenames based on VERSIONS

gtgtgt fileobjectversions()[_versionstestfoldertestimage_admin_thumbnailjpg_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionversions()[]

Note The versions are not being generated

admin_versions()List all filenames based on ADMIN_VERSIONS

gtgtgt fileobjectadmin_versions()[_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg

21 API 17

Django FileBrowser Documentation Release 357

_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionadmin_versions()[]

Note The versions are not being generated

version_name(version_suffix)Get the filename for a version

gtgtgt fileobjectversion_name(medium)testimage_mediumjpg

Note The version is not being generated

version_path(version_suffix)Get the path for a version

gtgtgt fileobjectversion_path(medium)_versionstestfoldertestimage_mediumjpg

Note The version is not being generated

version_generate(version_suffix)Generate a version

gtgtgt fileobjectversion_generate(medium)ltFileObject uploadstestfoldertestimage_mediumjpggt

Please note that a version is only generated if it does not already exist or if the original image is newer than theexisting version

Delete methods

delete()Delete the File or Folder from the server

Warning If you delete a Folder all items within the folder are being deleted

delete_versions()Delete all VERSIONS

delete_admin_versions()Delete all ADMIN_VERSIONS

18 Chapter 2 API

CHAPTER 3

Fields amp Widgets

31 Fields amp Widgets

The FileBrowseField is a custom model field which returns a FileObject The widgets FileInput and ClearableFileIn-put are used with the admin app in order to show an additional thumbnail for images

311 FileBrowseField

class FileBrowseField(max_length[ site directory extensions format options])A subclass of CharField referencing a media file within Returns a FileObject

Parameters

bull site ndash A FileBrowser site (defaults to the main site) see FileBrowser Site

bull directory ndash Directory to browse when clicking the search icon

bull extensions ndash List of allowed extensions see Extensions and Formats

bull format ndash A key from SELECT_FORMATS in order to restrict the selection to specificfiletypes see Extensions and Formats

For example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 directory=images extensions=[jpg] blank=True null=True)document = FileBrowseField(PDF max_length=200 directory=documents extensions=[pdfdoc] blank=True null=True)

FileBrowseField in Templates

You can use all attributes from FileObject

blogentryimage ltimg src= publicationimageurl gt

ifequal blogentryimageimage_orientation landscape ltimg src= blogentryimageurl class=landscape gt

endifequal

19

Django FileBrowser Documentation Release 357

Showing Thumbnail in the Changelist

To show a thumbnail with the changelist you can define a ModelAdmin method

from filebrowsersettings import ADMIN_THUMBNAIL

def image_thumbnail(self obj)if objimage and objimagefiletype == Image

return ltimg src=s gt objimageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Using the FileBrowseField with TinyMCE

In order to replace the TinyMCE imagefile manager with the FileBrowser you have to use a FileBrowser CallbackTherersquos an example TinyMCE configuration file in staticjs called TinyMCEAdminjs You can either copy theFileBrowserCallback to your own file or just use tinymce_setupjs (which comes with django-grappelli)

Just add these lines to your ModelAdmin asset definitions

class Mediajs = [pathtotinymcejscriptstiny_mcetiny_mcejs

pathtoyourtinymce_setupjs]

312 FileInput

Subclass of FileInput with an additional thumbnail

from filebrowserwidgets import FileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget FileInput

313 ClearableFileInput

Subclass of ClearableFileInput with an additional thumbnail

from filebrowserwidgets import ClearableFileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget ClearableFileInput

314 Django FileField and the FileBrowser

Return a FileObject from a FileField or ImageField with

20 Chapter 3 Fields amp Widgets

Django FileBrowser Documentation Release 357

from filebrowserbase import FileObject

image_upload = modelsImageField(uImage (Upload) max_length=250 upload_to=image_upload_path blank=True null=True)

def image(self)if selfimage_upload

return FileObject(selfimage_uploadpath)return None

In order show a thumbnail with your changelist you could use a ModelAdmin method

from filebrowserbase import FileObject

def image_thumbnail(self obj)if objimage_upload

image = FileObject(objimage_uploadpath)if imagefiletype == Image

return ltimg src=s gt imageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Note There are different ways to achieve this The above examples show one of several options

31 Fields amp Widgets 21

Django FileBrowser Documentation Release 357

22 Chapter 3 Fields amp Widgets

CHAPTER 4

Admin Interface

41 Admin Interface

The main FileBrowser admin application is an extension for the Django admin interface in order to browser yourmedia folder upload and renamedelete files

411 FileBrowser Site

New in version 340

class FileBrowserSite(name=None app_name=rsquofilebrowserrsquo storage=default_storage)Respresents the FileBrowser admin application (similar to Djangorsquos admin site)

Parameters

bull name ndash A name for the site defaults to None

bull app_name ndash Defaults to lsquofilebrowserrsquo

bull storage ndash A custom storage engine defaults to Djangos default storage

Similar to djangocontribadmin you first need to add a filebrowsersite to your admin interface Inyour urlspy import the default FileBrowser site (or your custom site) and add the site to your URL-patterns (beforeany admin-urls)

from filebrowsersites import site

urlpatterns = patterns(url(r^adminurlfilebrowser include(siteurls))

)

Now you are able to browse the location defined with the storage engine associated to your site

from djangocorefilesstorage import DefaultStoragefrom filebrowsersites import FileBrowserSite

Default FileBrowser sitesite = FileBrowserSite(name=filebrowser storage=DefaultStorage())

My Custom FileBrowser sitecustom_site = FileBrowserSite(name=custom_filebrowser storage=DefaultStorage())custom_sitedirectory = custom_uploads

23

Django FileBrowser Documentation Release 357

Note The module variable site from filebrowsersites is the default FileBrowser application

412 Custom Actions

New in version 340

Similar to Djangorsquos admin actions you can define your FileBrowser actions and thus automate the typical tasks ofyour users Registered custom actions are listed in the detail view of a file and a user can select a single action at atime The selected action will then be applied to the file

The default FileBrowser image actions such as ldquoFlip Verticalrdquo or ldquoRotate 90deg Clockwiserdquo are in fact implemented ascustom actions (see the module filebrowseractions)

Writing Your Own Actions

Custom actions are simple functions

def foo(request fileobjects) Do something with the fileobjects

The first parameter is a HttpRequest object (representing the submitted form in which a user selected the action)and the second parameter is a list of FileObjects to which the action should be applied

The list contains exactly one instance of FileObject (representing the file from the detail view) but this may change inthe future as custom actions may become available also in browse views (similar to admin actions applied to a list ofchecked objects)

Registering an Action

In order to make your action visible you need to register it with a FileBrowser site

siteadd_action(foo)

Once registered the action will appear in the detail view of a file You can also give your action a short description

fooshort_description = Do foo with the File

This short description will then appear in the list of available actions If you do not provide a short description thefunction name will be used instead and FileBrowser will replace any underscores in the function name with spaces

Associating Actions with Specific Files

Each custom action can be associated with a specific file type (eg images audio file etc) to which it applies In orderto do that you need to define a predicatefilter function which takes a single argument (FileObject) and returns Trueif your action is applicable to that FileObject Finally you need to register this filter function with your action

fooapplies_to(lambda fileobject fileobjectfiletype == Image)

In the above example foo will appear in the action list only for image files If you do not specify any filter functionfor your action FileBrowser considers the action as applicable to all files

24 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

Messages amp Intermediate Pages

You can provide a feedback to a user about a successful or failed execution of an action by using a message Forexample

from djangocontrib import messages

def desaturate_image(request fileobjects)for f in fileobjects

Desaturate the imagemessagesadd_message(request messagesSUCCESS _(Image s was desaturated) ffilename)

Some actions may require user confirmation (eg in order to prevent accidental and irreversible modification tofiles) In order to that follow the same pattern as with Djangorsquos admin action and return a HttpResponse objectfrom your action Good practice for intermediate pages is to implement a confirm view and have your action returnHttpResponseRedirect

def crop_image(request fileobjects)files = ampf=join([fpath_relative for f in fileobjects])return HttpResponseRedirect(confirmaction=crop_imageampf=s files)

413 File Storages

New in version 340

You have the option to specify which file storage engine a FileBrowser should use to browseuploadmodify yourmedia files This enables you to use a FileBrowser even if your media files are located at some remote system Seealso the Djangorsquos documentation on storages httpsdocsdjangoprojectcomendevtopicsfiles

To associate a FileBrowser site with a particular storage engine set the storage property of a site object

from djangocorefilesstorage import FileSystemStoragesitestorage = FileSystemStorage(location=pathtomediadirectory base_url=media)

For storage classes other than FileSystemStorage (or those that inherit from that class) therersquos more effort involved inproviding a storage object that can be used with FileBrowser See StorageMixin Class

Note Prior FileBrowser 34 the way to specify FileBrowserlsquos MEDIA_ROOT and MEDIA_URL was via settingspyStarting from version 34 those variables are associated with the storage instance and you can set them as illustratedin the above example

Warning For the reason of backward compatibility FileBrowser settings FILEBROWSER_MEDIA_ROOT andFILEBROWSER_MEDIA_URL can still be used to customize FileBrowser as long as yoursquore using the defaultFileBrowserlsquos site without having changed its storage engine In the next major release of FileBrowser thesesettings will be removed

StorageMixin Class

A FileBrowser uses the Djangorsquos Storage class to access media files However the API of the Storageclass does not provide all methods necessary for FileBrowserrsquos functionality A StorageMixin class fromfilebrowserstorage module therefore defines all the additional methods that a FileBrowser requires

isdir(self name)Returns true if name exists and is a directory

41 Admin Interface 25

Django FileBrowser Documentation Release 357

isfile(self name)Returns true if name exists and is a regular file

move(self old_file_name new_file_name allow_overwrite=False)Moves safely a file from one location to another If allow_ovewrite==False and new_file_nameexists raises an exception

makedirs(self name)Creates all missing directories specified by name Analogue to osmkdirs()

414 Views

All views use the staff_member_requird and path_exists decorator in order to check if the server pathactually exists Some views also use the file_exists decorator

bull Browse fb_browse Browse a directory on your server Returns a FileListing

ndash Optional query string args dir o ot q p filter_date filter_type type

bull Create directory fb_createdir Create a new folder on your server

ndash Optional query string args dir

ndash Signals filebrowser_pre_createdir filebrowser_post_createdir

bull Upload fb_upload Multiple upload

ndash Optional query string args dir type

ndash Signals filebrowser_pre_upload filebrowser_post_upload

bull Edit fb_edit Edit a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_rename filebrowser_post_rename

You are able to apply custom actions (see Custom Actions) to the edit-view

bull Confirm delete fb_confirm_delete Confirm the deletion of a file or folder

ndash Required query string args filename

ndash Optional query string args dir

If you try to delete a folder all filesfolders within this folder are listed on this page

bull Delete fb_delete Delete a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_delete filebrowser_post_delete

Warning If you delete a Folder all items within this Folder are being deleted

bull Version fb_version Generate a version of an image as defined with ADMIN_VERSIONS

ndash Required query string args filename

ndash Optional Query string args dir

This is a helper used by the FileBrowseField and TinyMCE for selecting a version

26 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

415 Signals

The FileBrowser sends a couple of different signals Please take a look at the module filebrowsersignals for furtherexplanation on the provided arguments

bull filebrowser_pre_upload Sent before a an Upload starts

bull filebrowser_post_upload Sent after an Upload has finished

bull filebrowser_pre_delete Sent before an Item (File Folder) is deleted

bull filebrowser_post_delete Sent after an Item (File Folder) has been deleted

bull filebrowser_pre_createdir Sent before a new Folder is created

bull filebrowser_post_createdir Sent after a new Folder has been created

bull filebrowser_pre_rename Sent before an Item (File Folder) is renamed

bull filebrowser_post_rename Sent after an Item (File Folder) has been renamed

bull filebrowser_actions_pre_apply Sent before a custom action is applied

bull filebrowser_actions_post_apply Sent after a custom action has been applied

Example for using these Signals

Herersquos a small example for using the above Signals

from filebrowser import signals

def pre_upload_callback(sender kwargs)Receiver function called before an upload startsprint Pre Upload Callbackprint kwargs kwargs

signalsfilebrowser_pre_uploadconnect(pre_upload_callback)

def post_upload_callback(sender kwargs)Receiver function called each time an upload has finishedprint Post Upload Callbackprint kwargs kwargs You can use all attributes available with the FileObject This is just an example print Filesize kwargs[file]filesizeprint Orientation kwargs[file]orientationprint Extension kwargs[file]extension

signalsfilebrowser_post_uploadconnect(post_upload_callback)

41 Admin Interface 27

Django FileBrowser Documentation Release 357

28 Chapter 4 Admin Interface

CHAPTER 5

Image Versions

51 Versions

With the FileBrowser you are able to define different versionssizes for images This enables you to save an originalimage on your server while having different versions of that image to automatically fit your websites grid Versionsare also useful for responsiveadaptive layouts

511 Defining Versions

New in version 340 methods

First you need to know which versionssizes of an image yoursquod like to generate with your website Letrsquos say yoursquoreusing a 12 column grid with 60px for each column and 20px margin (which is a total of 940px) With this grid youcould (for example) define these image versions

FILEBROWSER_VERSIONS_BASEDIR = _versionsFILEBROWSER_VERSIONS =

admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

Use the methods argument if you need to add a filter

def grayscale(im)Convert image to grayscaleif immode = L

im = imconvert(L)return im

FILEBROWSER_VERSIONS = big verbose_name Big (6 col) width 460 height opts methods [grayscale]

)

29

Django FileBrowser Documentation Release 357

512 Versions and the Admin

When using the FileBrowser with the admin interface you need to define ADMIN_VERSIONS andADMIN_THUMBNAIL (see Settings) ADMIN_VERSIONS are available with the admin ie you are able to seethese versions with the image detail view and you are able to select the versions with the FileBrowseField model field

FILEBROWSER_ADMIN_VERSIONS = [thumbnail small medium big large]FILEBROWSER_ADMIN_THUMBNAIL = admin_thumbnail

513 Versions and the Frontend

With your templates you have two different tags to choose from version and version_object With bothtags the version will be generated if it doesnrsquot already exist OR if the original image is newer than the version Inorder to update an image you just overwrite the original image and the versions will be generated automatically (asyou request them within your template)

A Model example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 blank=True null=True)

With your templates use version if you simply need to retrieve the URL or version_object if you need to geta FileObject

lt-- load filebrowser templatetags --gt load fb_versions

lt-- get the url with version --gtltimg src= version blogentryimage medium gt

lt-- get a fileobject with version_object --gt version_object blogentryimage medium as version_medium version_mediumwidth ltimg src= version_medium gt

Templatetag version

RetrievesGenerates a version and returns an URL

version modelfield_name version_prefix

Templatetag version_object

RetrievesGenerates a version and returns a FileObject

version_object modelfield_name version_prefix as variable

Note With both templatetags version_prefix can either be a string or a variable If version_prefix is astring use quotes

30 Chapter 5 Image Versions

Django FileBrowser Documentation Release 357

514 Versions in Views

If you have a FileObject you can generateretrieve a version with

v = objimageversion_generate(version_prefix) returns a FileObject

515 Placeholder

When developing on a locale machine or a development-server you might not have all the images (resp media-files)available that are on your production instance and downloading these files on a regular basis might not be an option

In that case you can use a placeholder instead of a version You just need to define the PLACEHOLDER and overwritethe settings SHOW_PLACEHOLDER andor FORCE_PLACEHOLDER (see Placeholder)

516 Management Commands

fb_version_generateIf you need to generate certain (or all) versions type

python managepy fb_version_generate

fb_version_removeIf you need to generate certain (or all) versions type

python managepy fb_version_generate

Warning Please be very careful with this command

51 Versions 31

Django FileBrowser Documentation Release 357

32 Chapter 5 Image Versions

CHAPTER 6

Help

61 Help

611 FAQ

Why should I use the FileBrowser

If you need your editors or customers to manage files the FileBrowser is an alternative to an FTP-client Moreoveryou are able to define different image versions according to your websites grid Alternatives to the FileBrowser can befound at httpdjangopackagescomgridsgfile-managers

Do I need Grappelli

Grappelli is a requirement for using the FileBrowser There are several filebrowser-no-grappelli repositories (most ofthem on GitHub) but we donrsquot follow the development

I need help

see Troubleshooting

Why are there no fancy effects

The FileBrowser is about managing files We think that you should prepare your files before uploading them to theserver

How do I upload to another server

Use a custom storage engine see httpsdocsdjangoprojectcomen16howtocustom-file-storage

Why do I need image-versions

You need image-versions if your website is based on a grid

33

Django FileBrowser Documentation Release 357

Is the FileBrowser stable

Wersquove developed the FileBrowser for a couple of years and use it with almost all of our clients That said Grappelli isthe more stable and mature application

How can I contribute

Help is very much needed and appreciated Test the FileBrowser and submit feedbackpatches

Who develops the FileBrowser

The FileBrowser is developed and maintained by Patrick Kranzlmuumlller amp Axel Swoboda of vonautomatisch

612 Troubleshooting

Check your setup

Please check if the problem is caused by your setup

bull Read Quick start guide

bull Check if the staticmedia-files are served correctly

bull Make sure you have removed all custom FileBrowser templates from all locations in TEMPLATE_DIRS orcheck that these templates are compatible with the FileBrowser

Run the tests

Start the shell and type

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Check issues

If your setup is fine please check if your problem is a known issue

bull Take a look at all FileBrowser Issues (incuding closed) and search the FileBrowser Google-Group

Add a ticket

If you think yoursquove found a bug please add a ticket

bull Try to describe your problem as precisely as possible

bull Tell us what you did in order to solve the problem

bull Tell us what version of the FileBrowser you are using

bull Tell us what version of Django you are using

34 Chapter 6 Help

Django FileBrowser Documentation Release 357

bull Please do NOT add tickets if yoursquore having problems with serving staticmedia-files (because this is not relatedto the FileBrowser)

bull Please do NOT add tickets referring to Djangos trunk version

bull At best add a patch

Note Be aware that we may close issues not following these guidlines without further notifications

613 Translation

Translation is done via Transifex

Supported Languages

see httpswwwtransifexnetprojectspdjango-filebrowserresourcedjangopo

614 FileBrowser 35 Release Notes

FileBrowser 35 is compatible with Django 14151617 as well as Grappelli 242526

Update from FileBrowser 34x

bull Update Django to 14151617 and check httpsdocsdjangoprojectcomendevreleases14 orhttpsdocsdjangoprojectcomendevreleases15 or httpsdocsdjangoprojectcomendevreleases16

bull Update Grappelli to 24x25x26x

bull Update FileBrowser to 35x

62 Changelog

621 358 (not yet released)

622 357 (September 10th 2014)

bull New Compatibility with Django 17 and Grappelli 26x

bull Improved Updated tests because of the new random suffix with get_available_name (django storage)

bull Improved Added an icon in order to mark finished uploads

bull Improved Show resulting filename (eg with suffix converted) after successful upload

bull Fixed Permissions with file upload

bull Fixed Unified json response with _upload_file (no matter if file already exists or not)

623 356 (April 16th 2014)

bull Fixed Displaying pagination correctly with lots of entries

62 Changelog 35

Django FileBrowser Documentation Release 357

624 355 (April 13th 2014)

bull New Added client-side (JavaScript) file extension validation to the AJAX uploader

bull New Added experimental Python 33 support

bull Improved Tests with convertnormalize (removed special chars from test filename)

bull Fixed File selection after using search box (CKEditor)

bull Fixed Removed encoding of file URIs with CKEditor

625 354 (February 21st 2014)

bull Fixed Placeholder functionality (including tests)

bull Fixed Convertnormalize filenames (including tests)

bull Fixed Handling uppercase extensions with browse

626 353 (January 7 2014)

bull New added path_full to FileObject

bull Improved added docx to EXTENSIONS

bull Improved Recommend pillow instead of PIL as a requirement

bull Improved Added additional test cases

bull Improved Updated documentation

bull Improved Consistent use of storage (eg storagelocation storageurl)

bull Improved Removed unnecessary functions (eg url_join url_strip)

bull Improved Moved sort_by_attr to FileListing

bull Improved Regex matches with file versions on browse

bull Improved Using djangoconfurls (with djangoconfurlsdefaults as fallback)

bull Improved Adding CONTRIBUTINGrst

bull Improved Removed static Media inner class with fields

bull Improved Removed search icon with fields (has not being used)

bull Improved Added custom class attributes with filebrowser field

bull Improved Updated translations

bull Fixed fixed exception handling with python 25

bull Fixed fixes dir with SEARCH_TRAVERSE true and version select

bull Fixed Make Django FileUploadHandlers work (also fixed a memory leak)

bull Fixed return correct filename with OVERWRITE_EXISTING

bull Fixed fb_version_generate with FILEBROWSER_VERSIONS_BASEDIR

bull Fixed Table sorting with ascdesc

bull Fixed Added DeprecationWarning for FileObjectdirectory and FileObjectfolder

36 Chapter 6 Help

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

Django FileBrowser Documentation Release 357

VERSIONS_BASEDIR = getattr(settings FILEBROWSER_VERSIONS_BASEDIR )

We do recommend the following structure for media files

-- media sitestoragelocation (eg MEDIA_ROOT)-- _versions VERSIONS_BASEDIR (outside of sitedirectory)-- uploads sitedirectory

Warning If VERSIONS_BASEDIR is within sitedirectory it will be browsed

Warning With the next major release (360) the default setting will be ldquo_versionsrdquo

VERSIONS

Define the versions according to your websites grid

VERSIONS = getattr(settings FILEBROWSER_VERSIONS admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

)

VERSION_QUALITY

Quality of saved versions

VERSION_QUALITY = getattr(settings FILEBROWSER_VERSION_QUALITY 90)

ADMIN_VERSIONS

The versions you want to show with the admin interface

ADMIN_VERSIONS = getattr(settings FILEBROWSER_ADMIN_VERSIONS [thumbnail small medium big large])

ADMIN_THUMBNAIL

The version being used as the admin thumbnail

ADMIN_THUMBNAIL = getattr(settings FILEBROWSER_ADMIN_THUMBNAIL admin_thumbnail)

125 Placeholder

With your locale environment you donrsquot necessarily have access to all media files (eg images uploaded by yourclient) Therefore you can use a PLACEHOLDER

6 Chapter 1 Installation and Setup

Django FileBrowser Documentation Release 357

PLACEHOLDER

Path to placeholder image (relative to storage location)

PLACEHOLDER = getattr(settings FILEBROWSER_PLACEHOLDER )

SHOW_PLACEHOLDER

Show placeholder (instead of a version) if the original image does not exist

SHOW_PLACEHOLDER = getattr(settings FILEBROWSER_SHOW_PLACEHOLDER False)

FORCE_PLACEHOLDER

Always show placeholder (even if the original image exists)

FORCE_PLACEHOLDER = getattr(settings FILEBROWSER_FORCE_PLACEHOLDER False)

126 Extra Settings

SAVE_FULL_URL

Deprecated since version 340 With custom storage engines saving the full URL doesnrsquot make sense anymoreMoreover removing this settings allows for easily replacing a FileBrowseField with Djangos File- or ImageField

STRICT_PIL

If set to True the FileBrowser will not try to import a mis-installed PIL

STRICT_PIL = getattr(settings FILEBROWSER_STRICT_PIL False)

IMAGE_MAXBLOCK

see httpmailpythonorgpipermailimage-sig1999-August000816html

IMAGE_MAXBLOCK = getattr(settings FILEBROWSER_IMAGE_MAXBLOCK 10241024)

EXCLUDE

Exclude-patterns for files you donrsquot want to show

EXTENSION_LIST = []for exts in EXTENSIONSvalues()

EXTENSION_LIST += extsEXCLUDE = getattr(settings FILEBROWSER_EXCLUDE (r_((exts)s)__qd13((exts)s) exts (|join(EXTENSION_LIST))))

12 Settings 7

Django FileBrowser Documentation Release 357

MAX_UPLOAD_SIZE

Max Upload Size in Bytes

MAX_UPLOAD_SIZE = getattr(settings FILEBROWSER_MAX_UPLOAD_SIZE 10485760)

NORMALIZE_FILENAME

True if you want to normalize filename on upload and remove all non-alphanumeric characters (except for under-scores spaces amp dashes)

NORMALIZE_FILENAME = getattr(settings FILEBROWSER_NORMALIZE_FILENAME False)

CONVERT_FILENAME

True if you want to convert the filename on upload (replace spaces and convert to lowercase)

CONVERT_FILENAME = getattr(settings FILEBROWSER_CONVERT_FILENAME True)

LIST_PER_PAGE

How many items appear on each paginated list

LIST_PER_PAGE = getattr(settings FILEBROWSER_LIST_PER_PAGE 50)

DEFAULT_SORTING_BY

Default sorting attribute

DEFAULT_SORTING_BY = getattr(settings FILEBROWSER_DEFAULT_SORTING_BY date)

Options are date filesize filename_lower filetype_checked

DEFAULT_SORTING_ORDER

Default sorting order

DEFAULT_SORTING_ORDER = getattr(settings FILEBROWSER_DEFAULT_SORTING_ORDER desc)

Options are asc or desc

FOLDER_REGEX

regex to clean directory names before creation

FOLDER_REGEX = getattr(settings FILEBROWSER_FOLDER_REGEX r^[w_ -]+$)

8 Chapter 1 Installation and Setup

Django FileBrowser Documentation Release 357

SEARCH_TRAVERSE

True if you want to traverse all subdirectories when searching Please note that with thousands of filesdirectoriesthis might take a while

SEARCH_TRAVERSE = getattr(settings FILEBROWSER_SEARCH_TRAVERSE False)

DEFAULT_PERMISSIONS

Default upload and version permissions

DEFAULT_PERMISSIONS = getattr(settings FILEBROWSER_DEFAULT_PERMISSIONS 0755)

OVERWRITE_EXISTING

New in version 351

True in order to overwrite existing files False to use the behaviour of the storage engine

OVERWRITE_EXISTING = getattr(settings FILEBROWSER_OVERWRITE_EXISTING True)

12 Settings 9

Django FileBrowser Documentation Release 357

10 Chapter 1 Installation and Setup

CHAPTER 2

API

21 API

211 FileListing

class FileListing(path filter_func=None sorting_by=None sorting_order=None)Returns a list of FileObjects for a server path see FileObject

Parameters

bull path ndash Relative path to a location within sitestoragelocation

bull filter_func ndash Filter function see example below

bull sorting_by ndash Sort the files by any attribute of FileObject

bull sorting_order ndash Sorting order either ldquoascrdquo or ldquodescrdquo

If you want to list all files within a storage location you do

from filebrowsersites import sitefrom filebrowserbase import FileListingfilelisting = FileListing(sitestoragelocation sorting_by=date sorting_order=desc)

Use a custom filter function to limit the list of files

def filter_filelisting(item) item is a FileObjectreturn itemfiletype = Folder

filelisting = FileListing(sitestoragelocation filter_func=filter_listing sorting_by=date sorting_order=desc)

Methods

For the below examples wersquore using this folder-structure

mediauploadstestfoldertestimagejpgmediauploadsblog1imagesblogimagejpg

Note We defined filter_browse as filter_func (see sitespy) And we did not define aVERSIONS_BASEDIR for this demonstration though it is highly recommended to use one

11

Django FileBrowser Documentation Release 357

listing()Returns all items for the given path with oslistdir(path)

gtgtgt for item in filelistinglisting() print itemblogtestfolder

walk()Returns all items for the given path with oswalk(path)

gtgtgt for item in filelistingwalk() print itemblogblog1blog1imagesblog1imagesblogimagejpgblog1imagesblogimage_admin_thumbnailjpgblog1imagesblogimage_mediumjpgblog1imagesblogimage_smalljpgblog1imagesblogimage_thumbnailjpgtestfoldertestfoldertestimagejpg

files_listing_total()Returns a sorted list of FileObjects for listing()

gtgtgt for item in filelistingfiles_listing_total() print itemuploadsbloguploadstestfolder

files_walk_total()Returns a sorted list of FileObjects for walk()

gtgtgt for item in filelistingfiles_walk_total() print itemuploadsbloguploadsblog1uploadsblog1imagesuploadsblog1imagesblogimagejpguploadsblog1imagesblogimage_admin_thumbnailjpguploadsblog1imagesblogimage_mediumjpguploadsblog1imagesblogimage_smalljpguploadsblog1imagesblogimage_thumbnailjpguploadstestfolderuploadstestfoldertestimagejpg

files_listing_filtered()Returns a sorted and filtered list of FileObjects for listing()

gtgtgt for item in filelistingfiles_listing_filtered() print itemuploadsbloguploadstestfolder

files_walk_filtered()Returns a sorted and filtered list of FileObjects for walk()

12 Chapter 2 API

Django FileBrowser Documentation Release 357

gtgtgt for item in filelistingfiles_walk_filtered() print itemuploadsbloguploadsblog1uploadsblog1imagesuploadsblog1imagesblogimagejpguploadstestfolderuploadstestfoldertestimagejpg

Note The versions are not listed (compared with files_walk_total) because of filter_func

results_listing_total()Number of total files based on files_listing_total()

gtgtgt filelistingresults_listing_total()2

results_walk_total()Number of total files based on files_walk_total()

gtgtgt filelistingresults_walk_total()10

results_listing_filtered()Number of filtered files based on files_listing_filtered()

gtgtgt filelistingresults_listing_filtered()2

results_walk_filtered()Number of filtered files based on files_walk_filtered()

gtgtgt filelistingresults_walk_filtered()6

212 FileObject

class FileObject(path site=None)An object representing a media file

Parameters

bull path ndash Relative path to a location within sitestoragelocation

bull site ndash An optional FileBrowser Site

For example

from filebrowsersites import sitefrom filebrowserbase import FileObjectfileobject = FileObject(ospathjoin(sitedirectorytestfoldertestimagejpg))version = FileObject(ospathjoin(fileobjectversions_basedir testfolder testimage_mediumjpg))

21 API 13

Django FileBrowser Documentation Release 357

Attributes

Initial Attributes

pathPath relative to a storage location (including sitedirectory)

gtgtgt fileobjectpathuploadstestfoldertestimagejpg

headThe directory name of pathname path

gtgtgt fileobjectheaduploadstestfolder

filenameName of the file (including the extension) or name of the folder

gtgtgt fileobjectfilenametestimagejpg

filename_lowerLower type of filename

filename_rootFilename without extension

gtgtgt fileobjectfilename_roottestimage

extensionFile extension including the dot With a folder the extensions is None

gtgtgt fileobjectextensionjpg

mimetypeMimetype based on httpdocspythonorglibrarymimetypeshtml

gtgtgt fileobjectmimetype(imagejpeg None)

General Attributes

filetypeType of the file as defined with EXTENSIONS

gtgtgt fileobjectfiletypeImage

filesizeFilesize in Bytes

gtgtgt fileobjectfilesize870037L

14 Chapter 2 API

Django FileBrowser Documentation Release 357

dateDate based on timemktime

gtgtgt fileobjectdate12997603470

datetimeDatetime object

gtgtgt fileobjectdatetimedatetimedatetime(2011 3 10 13 32 27)

existsTrue if the path exists False otherwise

gtgtgt fileobjectexistsTrue

Path and URL attributes

pathPath relative to a storage location (including sitedirectory)

gtgtgt fileobjectpathuploadstestfoldertestimagejpg

path_relative_directoryPath relative to sitedirectory

gtgtgt fileobjectpath_relative_directorytestfoldertestimagejpg

path_fullAbsolute server path (based on storagepath)

gtgtgt fileobjectpath_fullabsolutepathtoserverlocationtestfoldertestimagejpg

dirnameNew in version 34

The directory (not including sitedirectory)

gtgtgt fileobjectdirnametestfolder

urlURL for the filefolder (based on storageurl)

gtgtgt fileobjecturlmediauploadstestfoldertestimagejpg

Image attributes

The image attributes are only useful if the FileObject represents an image

dimensionsImage dimensions as a tuple

21 API 15

Django FileBrowser Documentation Release 357

gtgtgt fileobjectdimensions(1000 750)

widthImage width in px

gtgtgt fileobjectwidth1000

heightImage height in px

gtgtgt fileobjectheight750

aspectratioAspect ratio (float format)

gtgtgt fileobjectaspectratio133534908

orientationImage orientation either Landscape or Portrait

gtgtgt fileobjectorientationLandscape

Folder attributes

The folder attributes make sense when the FileObject represents a directory (not a file)

directory

Deprecated since version 353 Use path_relative_directory instead

folder

Deprecated since version 353 Use dirname instead

is_folderTrue if path is a folder

gtgtgt fileobjectis_folderFalse

is_emptyTrue if the folder is empty False if the folder is not empty or the FileObject is not a folder

gtgtgt fileobjectis_emptyFalse

Version attributes

is_versiontrue if the File is a version of another File

16 Chapter 2 API

Django FileBrowser Documentation Release 357

gtgtgt fileobjectis_versionFalsegtgtgt versionis_versionTrue

versions_basedirThe relative path (from storage location) to the main versions folder Either VERSIONS_BASEDIR orsitedirectory

gtgtgt fileobjectversions_basedir_versionsgtgtgt versionversions_basedir_versions

originalReturns the original FileObject

gtgtgt fileobjectoriginalltFileObject uploadstestfoldertestimagejpggtgtgtgt versionoriginalltFileObject uploadstestfoldertestimagejpggt

original_filenameGet the filename of an original image from a version

gtgtgt fileobjectoriginal_filenametestimagejpggtgtgt versionoriginal_filenametestimagejpg

Methods

Version methods

versions()List all filenames based on VERSIONS

gtgtgt fileobjectversions()[_versionstestfoldertestimage_admin_thumbnailjpg_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionversions()[]

Note The versions are not being generated

admin_versions()List all filenames based on ADMIN_VERSIONS

gtgtgt fileobjectadmin_versions()[_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg

21 API 17

Django FileBrowser Documentation Release 357

_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionadmin_versions()[]

Note The versions are not being generated

version_name(version_suffix)Get the filename for a version

gtgtgt fileobjectversion_name(medium)testimage_mediumjpg

Note The version is not being generated

version_path(version_suffix)Get the path for a version

gtgtgt fileobjectversion_path(medium)_versionstestfoldertestimage_mediumjpg

Note The version is not being generated

version_generate(version_suffix)Generate a version

gtgtgt fileobjectversion_generate(medium)ltFileObject uploadstestfoldertestimage_mediumjpggt

Please note that a version is only generated if it does not already exist or if the original image is newer than theexisting version

Delete methods

delete()Delete the File or Folder from the server

Warning If you delete a Folder all items within the folder are being deleted

delete_versions()Delete all VERSIONS

delete_admin_versions()Delete all ADMIN_VERSIONS

18 Chapter 2 API

CHAPTER 3

Fields amp Widgets

31 Fields amp Widgets

The FileBrowseField is a custom model field which returns a FileObject The widgets FileInput and ClearableFileIn-put are used with the admin app in order to show an additional thumbnail for images

311 FileBrowseField

class FileBrowseField(max_length[ site directory extensions format options])A subclass of CharField referencing a media file within Returns a FileObject

Parameters

bull site ndash A FileBrowser site (defaults to the main site) see FileBrowser Site

bull directory ndash Directory to browse when clicking the search icon

bull extensions ndash List of allowed extensions see Extensions and Formats

bull format ndash A key from SELECT_FORMATS in order to restrict the selection to specificfiletypes see Extensions and Formats

For example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 directory=images extensions=[jpg] blank=True null=True)document = FileBrowseField(PDF max_length=200 directory=documents extensions=[pdfdoc] blank=True null=True)

FileBrowseField in Templates

You can use all attributes from FileObject

blogentryimage ltimg src= publicationimageurl gt

ifequal blogentryimageimage_orientation landscape ltimg src= blogentryimageurl class=landscape gt

endifequal

19

Django FileBrowser Documentation Release 357

Showing Thumbnail in the Changelist

To show a thumbnail with the changelist you can define a ModelAdmin method

from filebrowsersettings import ADMIN_THUMBNAIL

def image_thumbnail(self obj)if objimage and objimagefiletype == Image

return ltimg src=s gt objimageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Using the FileBrowseField with TinyMCE

In order to replace the TinyMCE imagefile manager with the FileBrowser you have to use a FileBrowser CallbackTherersquos an example TinyMCE configuration file in staticjs called TinyMCEAdminjs You can either copy theFileBrowserCallback to your own file or just use tinymce_setupjs (which comes with django-grappelli)

Just add these lines to your ModelAdmin asset definitions

class Mediajs = [pathtotinymcejscriptstiny_mcetiny_mcejs

pathtoyourtinymce_setupjs]

312 FileInput

Subclass of FileInput with an additional thumbnail

from filebrowserwidgets import FileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget FileInput

313 ClearableFileInput

Subclass of ClearableFileInput with an additional thumbnail

from filebrowserwidgets import ClearableFileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget ClearableFileInput

314 Django FileField and the FileBrowser

Return a FileObject from a FileField or ImageField with

20 Chapter 3 Fields amp Widgets

Django FileBrowser Documentation Release 357

from filebrowserbase import FileObject

image_upload = modelsImageField(uImage (Upload) max_length=250 upload_to=image_upload_path blank=True null=True)

def image(self)if selfimage_upload

return FileObject(selfimage_uploadpath)return None

In order show a thumbnail with your changelist you could use a ModelAdmin method

from filebrowserbase import FileObject

def image_thumbnail(self obj)if objimage_upload

image = FileObject(objimage_uploadpath)if imagefiletype == Image

return ltimg src=s gt imageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Note There are different ways to achieve this The above examples show one of several options

31 Fields amp Widgets 21

Django FileBrowser Documentation Release 357

22 Chapter 3 Fields amp Widgets

CHAPTER 4

Admin Interface

41 Admin Interface

The main FileBrowser admin application is an extension for the Django admin interface in order to browser yourmedia folder upload and renamedelete files

411 FileBrowser Site

New in version 340

class FileBrowserSite(name=None app_name=rsquofilebrowserrsquo storage=default_storage)Respresents the FileBrowser admin application (similar to Djangorsquos admin site)

Parameters

bull name ndash A name for the site defaults to None

bull app_name ndash Defaults to lsquofilebrowserrsquo

bull storage ndash A custom storage engine defaults to Djangos default storage

Similar to djangocontribadmin you first need to add a filebrowsersite to your admin interface Inyour urlspy import the default FileBrowser site (or your custom site) and add the site to your URL-patterns (beforeany admin-urls)

from filebrowsersites import site

urlpatterns = patterns(url(r^adminurlfilebrowser include(siteurls))

)

Now you are able to browse the location defined with the storage engine associated to your site

from djangocorefilesstorage import DefaultStoragefrom filebrowsersites import FileBrowserSite

Default FileBrowser sitesite = FileBrowserSite(name=filebrowser storage=DefaultStorage())

My Custom FileBrowser sitecustom_site = FileBrowserSite(name=custom_filebrowser storage=DefaultStorage())custom_sitedirectory = custom_uploads

23

Django FileBrowser Documentation Release 357

Note The module variable site from filebrowsersites is the default FileBrowser application

412 Custom Actions

New in version 340

Similar to Djangorsquos admin actions you can define your FileBrowser actions and thus automate the typical tasks ofyour users Registered custom actions are listed in the detail view of a file and a user can select a single action at atime The selected action will then be applied to the file

The default FileBrowser image actions such as ldquoFlip Verticalrdquo or ldquoRotate 90deg Clockwiserdquo are in fact implemented ascustom actions (see the module filebrowseractions)

Writing Your Own Actions

Custom actions are simple functions

def foo(request fileobjects) Do something with the fileobjects

The first parameter is a HttpRequest object (representing the submitted form in which a user selected the action)and the second parameter is a list of FileObjects to which the action should be applied

The list contains exactly one instance of FileObject (representing the file from the detail view) but this may change inthe future as custom actions may become available also in browse views (similar to admin actions applied to a list ofchecked objects)

Registering an Action

In order to make your action visible you need to register it with a FileBrowser site

siteadd_action(foo)

Once registered the action will appear in the detail view of a file You can also give your action a short description

fooshort_description = Do foo with the File

This short description will then appear in the list of available actions If you do not provide a short description thefunction name will be used instead and FileBrowser will replace any underscores in the function name with spaces

Associating Actions with Specific Files

Each custom action can be associated with a specific file type (eg images audio file etc) to which it applies In orderto do that you need to define a predicatefilter function which takes a single argument (FileObject) and returns Trueif your action is applicable to that FileObject Finally you need to register this filter function with your action

fooapplies_to(lambda fileobject fileobjectfiletype == Image)

In the above example foo will appear in the action list only for image files If you do not specify any filter functionfor your action FileBrowser considers the action as applicable to all files

24 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

Messages amp Intermediate Pages

You can provide a feedback to a user about a successful or failed execution of an action by using a message Forexample

from djangocontrib import messages

def desaturate_image(request fileobjects)for f in fileobjects

Desaturate the imagemessagesadd_message(request messagesSUCCESS _(Image s was desaturated) ffilename)

Some actions may require user confirmation (eg in order to prevent accidental and irreversible modification tofiles) In order to that follow the same pattern as with Djangorsquos admin action and return a HttpResponse objectfrom your action Good practice for intermediate pages is to implement a confirm view and have your action returnHttpResponseRedirect

def crop_image(request fileobjects)files = ampf=join([fpath_relative for f in fileobjects])return HttpResponseRedirect(confirmaction=crop_imageampf=s files)

413 File Storages

New in version 340

You have the option to specify which file storage engine a FileBrowser should use to browseuploadmodify yourmedia files This enables you to use a FileBrowser even if your media files are located at some remote system Seealso the Djangorsquos documentation on storages httpsdocsdjangoprojectcomendevtopicsfiles

To associate a FileBrowser site with a particular storage engine set the storage property of a site object

from djangocorefilesstorage import FileSystemStoragesitestorage = FileSystemStorage(location=pathtomediadirectory base_url=media)

For storage classes other than FileSystemStorage (or those that inherit from that class) therersquos more effort involved inproviding a storage object that can be used with FileBrowser See StorageMixin Class

Note Prior FileBrowser 34 the way to specify FileBrowserlsquos MEDIA_ROOT and MEDIA_URL was via settingspyStarting from version 34 those variables are associated with the storage instance and you can set them as illustratedin the above example

Warning For the reason of backward compatibility FileBrowser settings FILEBROWSER_MEDIA_ROOT andFILEBROWSER_MEDIA_URL can still be used to customize FileBrowser as long as yoursquore using the defaultFileBrowserlsquos site without having changed its storage engine In the next major release of FileBrowser thesesettings will be removed

StorageMixin Class

A FileBrowser uses the Djangorsquos Storage class to access media files However the API of the Storageclass does not provide all methods necessary for FileBrowserrsquos functionality A StorageMixin class fromfilebrowserstorage module therefore defines all the additional methods that a FileBrowser requires

isdir(self name)Returns true if name exists and is a directory

41 Admin Interface 25

Django FileBrowser Documentation Release 357

isfile(self name)Returns true if name exists and is a regular file

move(self old_file_name new_file_name allow_overwrite=False)Moves safely a file from one location to another If allow_ovewrite==False and new_file_nameexists raises an exception

makedirs(self name)Creates all missing directories specified by name Analogue to osmkdirs()

414 Views

All views use the staff_member_requird and path_exists decorator in order to check if the server pathactually exists Some views also use the file_exists decorator

bull Browse fb_browse Browse a directory on your server Returns a FileListing

ndash Optional query string args dir o ot q p filter_date filter_type type

bull Create directory fb_createdir Create a new folder on your server

ndash Optional query string args dir

ndash Signals filebrowser_pre_createdir filebrowser_post_createdir

bull Upload fb_upload Multiple upload

ndash Optional query string args dir type

ndash Signals filebrowser_pre_upload filebrowser_post_upload

bull Edit fb_edit Edit a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_rename filebrowser_post_rename

You are able to apply custom actions (see Custom Actions) to the edit-view

bull Confirm delete fb_confirm_delete Confirm the deletion of a file or folder

ndash Required query string args filename

ndash Optional query string args dir

If you try to delete a folder all filesfolders within this folder are listed on this page

bull Delete fb_delete Delete a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_delete filebrowser_post_delete

Warning If you delete a Folder all items within this Folder are being deleted

bull Version fb_version Generate a version of an image as defined with ADMIN_VERSIONS

ndash Required query string args filename

ndash Optional Query string args dir

This is a helper used by the FileBrowseField and TinyMCE for selecting a version

26 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

415 Signals

The FileBrowser sends a couple of different signals Please take a look at the module filebrowsersignals for furtherexplanation on the provided arguments

bull filebrowser_pre_upload Sent before a an Upload starts

bull filebrowser_post_upload Sent after an Upload has finished

bull filebrowser_pre_delete Sent before an Item (File Folder) is deleted

bull filebrowser_post_delete Sent after an Item (File Folder) has been deleted

bull filebrowser_pre_createdir Sent before a new Folder is created

bull filebrowser_post_createdir Sent after a new Folder has been created

bull filebrowser_pre_rename Sent before an Item (File Folder) is renamed

bull filebrowser_post_rename Sent after an Item (File Folder) has been renamed

bull filebrowser_actions_pre_apply Sent before a custom action is applied

bull filebrowser_actions_post_apply Sent after a custom action has been applied

Example for using these Signals

Herersquos a small example for using the above Signals

from filebrowser import signals

def pre_upload_callback(sender kwargs)Receiver function called before an upload startsprint Pre Upload Callbackprint kwargs kwargs

signalsfilebrowser_pre_uploadconnect(pre_upload_callback)

def post_upload_callback(sender kwargs)Receiver function called each time an upload has finishedprint Post Upload Callbackprint kwargs kwargs You can use all attributes available with the FileObject This is just an example print Filesize kwargs[file]filesizeprint Orientation kwargs[file]orientationprint Extension kwargs[file]extension

signalsfilebrowser_post_uploadconnect(post_upload_callback)

41 Admin Interface 27

Django FileBrowser Documentation Release 357

28 Chapter 4 Admin Interface

CHAPTER 5

Image Versions

51 Versions

With the FileBrowser you are able to define different versionssizes for images This enables you to save an originalimage on your server while having different versions of that image to automatically fit your websites grid Versionsare also useful for responsiveadaptive layouts

511 Defining Versions

New in version 340 methods

First you need to know which versionssizes of an image yoursquod like to generate with your website Letrsquos say yoursquoreusing a 12 column grid with 60px for each column and 20px margin (which is a total of 940px) With this grid youcould (for example) define these image versions

FILEBROWSER_VERSIONS_BASEDIR = _versionsFILEBROWSER_VERSIONS =

admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

Use the methods argument if you need to add a filter

def grayscale(im)Convert image to grayscaleif immode = L

im = imconvert(L)return im

FILEBROWSER_VERSIONS = big verbose_name Big (6 col) width 460 height opts methods [grayscale]

)

29

Django FileBrowser Documentation Release 357

512 Versions and the Admin

When using the FileBrowser with the admin interface you need to define ADMIN_VERSIONS andADMIN_THUMBNAIL (see Settings) ADMIN_VERSIONS are available with the admin ie you are able to seethese versions with the image detail view and you are able to select the versions with the FileBrowseField model field

FILEBROWSER_ADMIN_VERSIONS = [thumbnail small medium big large]FILEBROWSER_ADMIN_THUMBNAIL = admin_thumbnail

513 Versions and the Frontend

With your templates you have two different tags to choose from version and version_object With bothtags the version will be generated if it doesnrsquot already exist OR if the original image is newer than the version Inorder to update an image you just overwrite the original image and the versions will be generated automatically (asyou request them within your template)

A Model example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 blank=True null=True)

With your templates use version if you simply need to retrieve the URL or version_object if you need to geta FileObject

lt-- load filebrowser templatetags --gt load fb_versions

lt-- get the url with version --gtltimg src= version blogentryimage medium gt

lt-- get a fileobject with version_object --gt version_object blogentryimage medium as version_medium version_mediumwidth ltimg src= version_medium gt

Templatetag version

RetrievesGenerates a version and returns an URL

version modelfield_name version_prefix

Templatetag version_object

RetrievesGenerates a version and returns a FileObject

version_object modelfield_name version_prefix as variable

Note With both templatetags version_prefix can either be a string or a variable If version_prefix is astring use quotes

30 Chapter 5 Image Versions

Django FileBrowser Documentation Release 357

514 Versions in Views

If you have a FileObject you can generateretrieve a version with

v = objimageversion_generate(version_prefix) returns a FileObject

515 Placeholder

When developing on a locale machine or a development-server you might not have all the images (resp media-files)available that are on your production instance and downloading these files on a regular basis might not be an option

In that case you can use a placeholder instead of a version You just need to define the PLACEHOLDER and overwritethe settings SHOW_PLACEHOLDER andor FORCE_PLACEHOLDER (see Placeholder)

516 Management Commands

fb_version_generateIf you need to generate certain (or all) versions type

python managepy fb_version_generate

fb_version_removeIf you need to generate certain (or all) versions type

python managepy fb_version_generate

Warning Please be very careful with this command

51 Versions 31

Django FileBrowser Documentation Release 357

32 Chapter 5 Image Versions

CHAPTER 6

Help

61 Help

611 FAQ

Why should I use the FileBrowser

If you need your editors or customers to manage files the FileBrowser is an alternative to an FTP-client Moreoveryou are able to define different image versions according to your websites grid Alternatives to the FileBrowser can befound at httpdjangopackagescomgridsgfile-managers

Do I need Grappelli

Grappelli is a requirement for using the FileBrowser There are several filebrowser-no-grappelli repositories (most ofthem on GitHub) but we donrsquot follow the development

I need help

see Troubleshooting

Why are there no fancy effects

The FileBrowser is about managing files We think that you should prepare your files before uploading them to theserver

How do I upload to another server

Use a custom storage engine see httpsdocsdjangoprojectcomen16howtocustom-file-storage

Why do I need image-versions

You need image-versions if your website is based on a grid

33

Django FileBrowser Documentation Release 357

Is the FileBrowser stable

Wersquove developed the FileBrowser for a couple of years and use it with almost all of our clients That said Grappelli isthe more stable and mature application

How can I contribute

Help is very much needed and appreciated Test the FileBrowser and submit feedbackpatches

Who develops the FileBrowser

The FileBrowser is developed and maintained by Patrick Kranzlmuumlller amp Axel Swoboda of vonautomatisch

612 Troubleshooting

Check your setup

Please check if the problem is caused by your setup

bull Read Quick start guide

bull Check if the staticmedia-files are served correctly

bull Make sure you have removed all custom FileBrowser templates from all locations in TEMPLATE_DIRS orcheck that these templates are compatible with the FileBrowser

Run the tests

Start the shell and type

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Check issues

If your setup is fine please check if your problem is a known issue

bull Take a look at all FileBrowser Issues (incuding closed) and search the FileBrowser Google-Group

Add a ticket

If you think yoursquove found a bug please add a ticket

bull Try to describe your problem as precisely as possible

bull Tell us what you did in order to solve the problem

bull Tell us what version of the FileBrowser you are using

bull Tell us what version of Django you are using

34 Chapter 6 Help

Django FileBrowser Documentation Release 357

bull Please do NOT add tickets if yoursquore having problems with serving staticmedia-files (because this is not relatedto the FileBrowser)

bull Please do NOT add tickets referring to Djangos trunk version

bull At best add a patch

Note Be aware that we may close issues not following these guidlines without further notifications

613 Translation

Translation is done via Transifex

Supported Languages

see httpswwwtransifexnetprojectspdjango-filebrowserresourcedjangopo

614 FileBrowser 35 Release Notes

FileBrowser 35 is compatible with Django 14151617 as well as Grappelli 242526

Update from FileBrowser 34x

bull Update Django to 14151617 and check httpsdocsdjangoprojectcomendevreleases14 orhttpsdocsdjangoprojectcomendevreleases15 or httpsdocsdjangoprojectcomendevreleases16

bull Update Grappelli to 24x25x26x

bull Update FileBrowser to 35x

62 Changelog

621 358 (not yet released)

622 357 (September 10th 2014)

bull New Compatibility with Django 17 and Grappelli 26x

bull Improved Updated tests because of the new random suffix with get_available_name (django storage)

bull Improved Added an icon in order to mark finished uploads

bull Improved Show resulting filename (eg with suffix converted) after successful upload

bull Fixed Permissions with file upload

bull Fixed Unified json response with _upload_file (no matter if file already exists or not)

623 356 (April 16th 2014)

bull Fixed Displaying pagination correctly with lots of entries

62 Changelog 35

Django FileBrowser Documentation Release 357

624 355 (April 13th 2014)

bull New Added client-side (JavaScript) file extension validation to the AJAX uploader

bull New Added experimental Python 33 support

bull Improved Tests with convertnormalize (removed special chars from test filename)

bull Fixed File selection after using search box (CKEditor)

bull Fixed Removed encoding of file URIs with CKEditor

625 354 (February 21st 2014)

bull Fixed Placeholder functionality (including tests)

bull Fixed Convertnormalize filenames (including tests)

bull Fixed Handling uppercase extensions with browse

626 353 (January 7 2014)

bull New added path_full to FileObject

bull Improved added docx to EXTENSIONS

bull Improved Recommend pillow instead of PIL as a requirement

bull Improved Added additional test cases

bull Improved Updated documentation

bull Improved Consistent use of storage (eg storagelocation storageurl)

bull Improved Removed unnecessary functions (eg url_join url_strip)

bull Improved Moved sort_by_attr to FileListing

bull Improved Regex matches with file versions on browse

bull Improved Using djangoconfurls (with djangoconfurlsdefaults as fallback)

bull Improved Adding CONTRIBUTINGrst

bull Improved Removed static Media inner class with fields

bull Improved Removed search icon with fields (has not being used)

bull Improved Added custom class attributes with filebrowser field

bull Improved Updated translations

bull Fixed fixed exception handling with python 25

bull Fixed fixes dir with SEARCH_TRAVERSE true and version select

bull Fixed Make Django FileUploadHandlers work (also fixed a memory leak)

bull Fixed return correct filename with OVERWRITE_EXISTING

bull Fixed fb_version_generate with FILEBROWSER_VERSIONS_BASEDIR

bull Fixed Table sorting with ascdesc

bull Fixed Added DeprecationWarning for FileObjectdirectory and FileObjectfolder

36 Chapter 6 Help

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

Django FileBrowser Documentation Release 357

PLACEHOLDER

Path to placeholder image (relative to storage location)

PLACEHOLDER = getattr(settings FILEBROWSER_PLACEHOLDER )

SHOW_PLACEHOLDER

Show placeholder (instead of a version) if the original image does not exist

SHOW_PLACEHOLDER = getattr(settings FILEBROWSER_SHOW_PLACEHOLDER False)

FORCE_PLACEHOLDER

Always show placeholder (even if the original image exists)

FORCE_PLACEHOLDER = getattr(settings FILEBROWSER_FORCE_PLACEHOLDER False)

126 Extra Settings

SAVE_FULL_URL

Deprecated since version 340 With custom storage engines saving the full URL doesnrsquot make sense anymoreMoreover removing this settings allows for easily replacing a FileBrowseField with Djangos File- or ImageField

STRICT_PIL

If set to True the FileBrowser will not try to import a mis-installed PIL

STRICT_PIL = getattr(settings FILEBROWSER_STRICT_PIL False)

IMAGE_MAXBLOCK

see httpmailpythonorgpipermailimage-sig1999-August000816html

IMAGE_MAXBLOCK = getattr(settings FILEBROWSER_IMAGE_MAXBLOCK 10241024)

EXCLUDE

Exclude-patterns for files you donrsquot want to show

EXTENSION_LIST = []for exts in EXTENSIONSvalues()

EXTENSION_LIST += extsEXCLUDE = getattr(settings FILEBROWSER_EXCLUDE (r_((exts)s)__qd13((exts)s) exts (|join(EXTENSION_LIST))))

12 Settings 7

Django FileBrowser Documentation Release 357

MAX_UPLOAD_SIZE

Max Upload Size in Bytes

MAX_UPLOAD_SIZE = getattr(settings FILEBROWSER_MAX_UPLOAD_SIZE 10485760)

NORMALIZE_FILENAME

True if you want to normalize filename on upload and remove all non-alphanumeric characters (except for under-scores spaces amp dashes)

NORMALIZE_FILENAME = getattr(settings FILEBROWSER_NORMALIZE_FILENAME False)

CONVERT_FILENAME

True if you want to convert the filename on upload (replace spaces and convert to lowercase)

CONVERT_FILENAME = getattr(settings FILEBROWSER_CONVERT_FILENAME True)

LIST_PER_PAGE

How many items appear on each paginated list

LIST_PER_PAGE = getattr(settings FILEBROWSER_LIST_PER_PAGE 50)

DEFAULT_SORTING_BY

Default sorting attribute

DEFAULT_SORTING_BY = getattr(settings FILEBROWSER_DEFAULT_SORTING_BY date)

Options are date filesize filename_lower filetype_checked

DEFAULT_SORTING_ORDER

Default sorting order

DEFAULT_SORTING_ORDER = getattr(settings FILEBROWSER_DEFAULT_SORTING_ORDER desc)

Options are asc or desc

FOLDER_REGEX

regex to clean directory names before creation

FOLDER_REGEX = getattr(settings FILEBROWSER_FOLDER_REGEX r^[w_ -]+$)

8 Chapter 1 Installation and Setup

Django FileBrowser Documentation Release 357

SEARCH_TRAVERSE

True if you want to traverse all subdirectories when searching Please note that with thousands of filesdirectoriesthis might take a while

SEARCH_TRAVERSE = getattr(settings FILEBROWSER_SEARCH_TRAVERSE False)

DEFAULT_PERMISSIONS

Default upload and version permissions

DEFAULT_PERMISSIONS = getattr(settings FILEBROWSER_DEFAULT_PERMISSIONS 0755)

OVERWRITE_EXISTING

New in version 351

True in order to overwrite existing files False to use the behaviour of the storage engine

OVERWRITE_EXISTING = getattr(settings FILEBROWSER_OVERWRITE_EXISTING True)

12 Settings 9

Django FileBrowser Documentation Release 357

10 Chapter 1 Installation and Setup

CHAPTER 2

API

21 API

211 FileListing

class FileListing(path filter_func=None sorting_by=None sorting_order=None)Returns a list of FileObjects for a server path see FileObject

Parameters

bull path ndash Relative path to a location within sitestoragelocation

bull filter_func ndash Filter function see example below

bull sorting_by ndash Sort the files by any attribute of FileObject

bull sorting_order ndash Sorting order either ldquoascrdquo or ldquodescrdquo

If you want to list all files within a storage location you do

from filebrowsersites import sitefrom filebrowserbase import FileListingfilelisting = FileListing(sitestoragelocation sorting_by=date sorting_order=desc)

Use a custom filter function to limit the list of files

def filter_filelisting(item) item is a FileObjectreturn itemfiletype = Folder

filelisting = FileListing(sitestoragelocation filter_func=filter_listing sorting_by=date sorting_order=desc)

Methods

For the below examples wersquore using this folder-structure

mediauploadstestfoldertestimagejpgmediauploadsblog1imagesblogimagejpg

Note We defined filter_browse as filter_func (see sitespy) And we did not define aVERSIONS_BASEDIR for this demonstration though it is highly recommended to use one

11

Django FileBrowser Documentation Release 357

listing()Returns all items for the given path with oslistdir(path)

gtgtgt for item in filelistinglisting() print itemblogtestfolder

walk()Returns all items for the given path with oswalk(path)

gtgtgt for item in filelistingwalk() print itemblogblog1blog1imagesblog1imagesblogimagejpgblog1imagesblogimage_admin_thumbnailjpgblog1imagesblogimage_mediumjpgblog1imagesblogimage_smalljpgblog1imagesblogimage_thumbnailjpgtestfoldertestfoldertestimagejpg

files_listing_total()Returns a sorted list of FileObjects for listing()

gtgtgt for item in filelistingfiles_listing_total() print itemuploadsbloguploadstestfolder

files_walk_total()Returns a sorted list of FileObjects for walk()

gtgtgt for item in filelistingfiles_walk_total() print itemuploadsbloguploadsblog1uploadsblog1imagesuploadsblog1imagesblogimagejpguploadsblog1imagesblogimage_admin_thumbnailjpguploadsblog1imagesblogimage_mediumjpguploadsblog1imagesblogimage_smalljpguploadsblog1imagesblogimage_thumbnailjpguploadstestfolderuploadstestfoldertestimagejpg

files_listing_filtered()Returns a sorted and filtered list of FileObjects for listing()

gtgtgt for item in filelistingfiles_listing_filtered() print itemuploadsbloguploadstestfolder

files_walk_filtered()Returns a sorted and filtered list of FileObjects for walk()

12 Chapter 2 API

Django FileBrowser Documentation Release 357

gtgtgt for item in filelistingfiles_walk_filtered() print itemuploadsbloguploadsblog1uploadsblog1imagesuploadsblog1imagesblogimagejpguploadstestfolderuploadstestfoldertestimagejpg

Note The versions are not listed (compared with files_walk_total) because of filter_func

results_listing_total()Number of total files based on files_listing_total()

gtgtgt filelistingresults_listing_total()2

results_walk_total()Number of total files based on files_walk_total()

gtgtgt filelistingresults_walk_total()10

results_listing_filtered()Number of filtered files based on files_listing_filtered()

gtgtgt filelistingresults_listing_filtered()2

results_walk_filtered()Number of filtered files based on files_walk_filtered()

gtgtgt filelistingresults_walk_filtered()6

212 FileObject

class FileObject(path site=None)An object representing a media file

Parameters

bull path ndash Relative path to a location within sitestoragelocation

bull site ndash An optional FileBrowser Site

For example

from filebrowsersites import sitefrom filebrowserbase import FileObjectfileobject = FileObject(ospathjoin(sitedirectorytestfoldertestimagejpg))version = FileObject(ospathjoin(fileobjectversions_basedir testfolder testimage_mediumjpg))

21 API 13

Django FileBrowser Documentation Release 357

Attributes

Initial Attributes

pathPath relative to a storage location (including sitedirectory)

gtgtgt fileobjectpathuploadstestfoldertestimagejpg

headThe directory name of pathname path

gtgtgt fileobjectheaduploadstestfolder

filenameName of the file (including the extension) or name of the folder

gtgtgt fileobjectfilenametestimagejpg

filename_lowerLower type of filename

filename_rootFilename without extension

gtgtgt fileobjectfilename_roottestimage

extensionFile extension including the dot With a folder the extensions is None

gtgtgt fileobjectextensionjpg

mimetypeMimetype based on httpdocspythonorglibrarymimetypeshtml

gtgtgt fileobjectmimetype(imagejpeg None)

General Attributes

filetypeType of the file as defined with EXTENSIONS

gtgtgt fileobjectfiletypeImage

filesizeFilesize in Bytes

gtgtgt fileobjectfilesize870037L

14 Chapter 2 API

Django FileBrowser Documentation Release 357

dateDate based on timemktime

gtgtgt fileobjectdate12997603470

datetimeDatetime object

gtgtgt fileobjectdatetimedatetimedatetime(2011 3 10 13 32 27)

existsTrue if the path exists False otherwise

gtgtgt fileobjectexistsTrue

Path and URL attributes

pathPath relative to a storage location (including sitedirectory)

gtgtgt fileobjectpathuploadstestfoldertestimagejpg

path_relative_directoryPath relative to sitedirectory

gtgtgt fileobjectpath_relative_directorytestfoldertestimagejpg

path_fullAbsolute server path (based on storagepath)

gtgtgt fileobjectpath_fullabsolutepathtoserverlocationtestfoldertestimagejpg

dirnameNew in version 34

The directory (not including sitedirectory)

gtgtgt fileobjectdirnametestfolder

urlURL for the filefolder (based on storageurl)

gtgtgt fileobjecturlmediauploadstestfoldertestimagejpg

Image attributes

The image attributes are only useful if the FileObject represents an image

dimensionsImage dimensions as a tuple

21 API 15

Django FileBrowser Documentation Release 357

gtgtgt fileobjectdimensions(1000 750)

widthImage width in px

gtgtgt fileobjectwidth1000

heightImage height in px

gtgtgt fileobjectheight750

aspectratioAspect ratio (float format)

gtgtgt fileobjectaspectratio133534908

orientationImage orientation either Landscape or Portrait

gtgtgt fileobjectorientationLandscape

Folder attributes

The folder attributes make sense when the FileObject represents a directory (not a file)

directory

Deprecated since version 353 Use path_relative_directory instead

folder

Deprecated since version 353 Use dirname instead

is_folderTrue if path is a folder

gtgtgt fileobjectis_folderFalse

is_emptyTrue if the folder is empty False if the folder is not empty or the FileObject is not a folder

gtgtgt fileobjectis_emptyFalse

Version attributes

is_versiontrue if the File is a version of another File

16 Chapter 2 API

Django FileBrowser Documentation Release 357

gtgtgt fileobjectis_versionFalsegtgtgt versionis_versionTrue

versions_basedirThe relative path (from storage location) to the main versions folder Either VERSIONS_BASEDIR orsitedirectory

gtgtgt fileobjectversions_basedir_versionsgtgtgt versionversions_basedir_versions

originalReturns the original FileObject

gtgtgt fileobjectoriginalltFileObject uploadstestfoldertestimagejpggtgtgtgt versionoriginalltFileObject uploadstestfoldertestimagejpggt

original_filenameGet the filename of an original image from a version

gtgtgt fileobjectoriginal_filenametestimagejpggtgtgt versionoriginal_filenametestimagejpg

Methods

Version methods

versions()List all filenames based on VERSIONS

gtgtgt fileobjectversions()[_versionstestfoldertestimage_admin_thumbnailjpg_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionversions()[]

Note The versions are not being generated

admin_versions()List all filenames based on ADMIN_VERSIONS

gtgtgt fileobjectadmin_versions()[_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg

21 API 17

Django FileBrowser Documentation Release 357

_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionadmin_versions()[]

Note The versions are not being generated

version_name(version_suffix)Get the filename for a version

gtgtgt fileobjectversion_name(medium)testimage_mediumjpg

Note The version is not being generated

version_path(version_suffix)Get the path for a version

gtgtgt fileobjectversion_path(medium)_versionstestfoldertestimage_mediumjpg

Note The version is not being generated

version_generate(version_suffix)Generate a version

gtgtgt fileobjectversion_generate(medium)ltFileObject uploadstestfoldertestimage_mediumjpggt

Please note that a version is only generated if it does not already exist or if the original image is newer than theexisting version

Delete methods

delete()Delete the File or Folder from the server

Warning If you delete a Folder all items within the folder are being deleted

delete_versions()Delete all VERSIONS

delete_admin_versions()Delete all ADMIN_VERSIONS

18 Chapter 2 API

CHAPTER 3

Fields amp Widgets

31 Fields amp Widgets

The FileBrowseField is a custom model field which returns a FileObject The widgets FileInput and ClearableFileIn-put are used with the admin app in order to show an additional thumbnail for images

311 FileBrowseField

class FileBrowseField(max_length[ site directory extensions format options])A subclass of CharField referencing a media file within Returns a FileObject

Parameters

bull site ndash A FileBrowser site (defaults to the main site) see FileBrowser Site

bull directory ndash Directory to browse when clicking the search icon

bull extensions ndash List of allowed extensions see Extensions and Formats

bull format ndash A key from SELECT_FORMATS in order to restrict the selection to specificfiletypes see Extensions and Formats

For example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 directory=images extensions=[jpg] blank=True null=True)document = FileBrowseField(PDF max_length=200 directory=documents extensions=[pdfdoc] blank=True null=True)

FileBrowseField in Templates

You can use all attributes from FileObject

blogentryimage ltimg src= publicationimageurl gt

ifequal blogentryimageimage_orientation landscape ltimg src= blogentryimageurl class=landscape gt

endifequal

19

Django FileBrowser Documentation Release 357

Showing Thumbnail in the Changelist

To show a thumbnail with the changelist you can define a ModelAdmin method

from filebrowsersettings import ADMIN_THUMBNAIL

def image_thumbnail(self obj)if objimage and objimagefiletype == Image

return ltimg src=s gt objimageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Using the FileBrowseField with TinyMCE

In order to replace the TinyMCE imagefile manager with the FileBrowser you have to use a FileBrowser CallbackTherersquos an example TinyMCE configuration file in staticjs called TinyMCEAdminjs You can either copy theFileBrowserCallback to your own file or just use tinymce_setupjs (which comes with django-grappelli)

Just add these lines to your ModelAdmin asset definitions

class Mediajs = [pathtotinymcejscriptstiny_mcetiny_mcejs

pathtoyourtinymce_setupjs]

312 FileInput

Subclass of FileInput with an additional thumbnail

from filebrowserwidgets import FileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget FileInput

313 ClearableFileInput

Subclass of ClearableFileInput with an additional thumbnail

from filebrowserwidgets import ClearableFileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget ClearableFileInput

314 Django FileField and the FileBrowser

Return a FileObject from a FileField or ImageField with

20 Chapter 3 Fields amp Widgets

Django FileBrowser Documentation Release 357

from filebrowserbase import FileObject

image_upload = modelsImageField(uImage (Upload) max_length=250 upload_to=image_upload_path blank=True null=True)

def image(self)if selfimage_upload

return FileObject(selfimage_uploadpath)return None

In order show a thumbnail with your changelist you could use a ModelAdmin method

from filebrowserbase import FileObject

def image_thumbnail(self obj)if objimage_upload

image = FileObject(objimage_uploadpath)if imagefiletype == Image

return ltimg src=s gt imageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Note There are different ways to achieve this The above examples show one of several options

31 Fields amp Widgets 21

Django FileBrowser Documentation Release 357

22 Chapter 3 Fields amp Widgets

CHAPTER 4

Admin Interface

41 Admin Interface

The main FileBrowser admin application is an extension for the Django admin interface in order to browser yourmedia folder upload and renamedelete files

411 FileBrowser Site

New in version 340

class FileBrowserSite(name=None app_name=rsquofilebrowserrsquo storage=default_storage)Respresents the FileBrowser admin application (similar to Djangorsquos admin site)

Parameters

bull name ndash A name for the site defaults to None

bull app_name ndash Defaults to lsquofilebrowserrsquo

bull storage ndash A custom storage engine defaults to Djangos default storage

Similar to djangocontribadmin you first need to add a filebrowsersite to your admin interface Inyour urlspy import the default FileBrowser site (or your custom site) and add the site to your URL-patterns (beforeany admin-urls)

from filebrowsersites import site

urlpatterns = patterns(url(r^adminurlfilebrowser include(siteurls))

)

Now you are able to browse the location defined with the storage engine associated to your site

from djangocorefilesstorage import DefaultStoragefrom filebrowsersites import FileBrowserSite

Default FileBrowser sitesite = FileBrowserSite(name=filebrowser storage=DefaultStorage())

My Custom FileBrowser sitecustom_site = FileBrowserSite(name=custom_filebrowser storage=DefaultStorage())custom_sitedirectory = custom_uploads

23

Django FileBrowser Documentation Release 357

Note The module variable site from filebrowsersites is the default FileBrowser application

412 Custom Actions

New in version 340

Similar to Djangorsquos admin actions you can define your FileBrowser actions and thus automate the typical tasks ofyour users Registered custom actions are listed in the detail view of a file and a user can select a single action at atime The selected action will then be applied to the file

The default FileBrowser image actions such as ldquoFlip Verticalrdquo or ldquoRotate 90deg Clockwiserdquo are in fact implemented ascustom actions (see the module filebrowseractions)

Writing Your Own Actions

Custom actions are simple functions

def foo(request fileobjects) Do something with the fileobjects

The first parameter is a HttpRequest object (representing the submitted form in which a user selected the action)and the second parameter is a list of FileObjects to which the action should be applied

The list contains exactly one instance of FileObject (representing the file from the detail view) but this may change inthe future as custom actions may become available also in browse views (similar to admin actions applied to a list ofchecked objects)

Registering an Action

In order to make your action visible you need to register it with a FileBrowser site

siteadd_action(foo)

Once registered the action will appear in the detail view of a file You can also give your action a short description

fooshort_description = Do foo with the File

This short description will then appear in the list of available actions If you do not provide a short description thefunction name will be used instead and FileBrowser will replace any underscores in the function name with spaces

Associating Actions with Specific Files

Each custom action can be associated with a specific file type (eg images audio file etc) to which it applies In orderto do that you need to define a predicatefilter function which takes a single argument (FileObject) and returns Trueif your action is applicable to that FileObject Finally you need to register this filter function with your action

fooapplies_to(lambda fileobject fileobjectfiletype == Image)

In the above example foo will appear in the action list only for image files If you do not specify any filter functionfor your action FileBrowser considers the action as applicable to all files

24 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

Messages amp Intermediate Pages

You can provide a feedback to a user about a successful or failed execution of an action by using a message Forexample

from djangocontrib import messages

def desaturate_image(request fileobjects)for f in fileobjects

Desaturate the imagemessagesadd_message(request messagesSUCCESS _(Image s was desaturated) ffilename)

Some actions may require user confirmation (eg in order to prevent accidental and irreversible modification tofiles) In order to that follow the same pattern as with Djangorsquos admin action and return a HttpResponse objectfrom your action Good practice for intermediate pages is to implement a confirm view and have your action returnHttpResponseRedirect

def crop_image(request fileobjects)files = ampf=join([fpath_relative for f in fileobjects])return HttpResponseRedirect(confirmaction=crop_imageampf=s files)

413 File Storages

New in version 340

You have the option to specify which file storage engine a FileBrowser should use to browseuploadmodify yourmedia files This enables you to use a FileBrowser even if your media files are located at some remote system Seealso the Djangorsquos documentation on storages httpsdocsdjangoprojectcomendevtopicsfiles

To associate a FileBrowser site with a particular storage engine set the storage property of a site object

from djangocorefilesstorage import FileSystemStoragesitestorage = FileSystemStorage(location=pathtomediadirectory base_url=media)

For storage classes other than FileSystemStorage (or those that inherit from that class) therersquos more effort involved inproviding a storage object that can be used with FileBrowser See StorageMixin Class

Note Prior FileBrowser 34 the way to specify FileBrowserlsquos MEDIA_ROOT and MEDIA_URL was via settingspyStarting from version 34 those variables are associated with the storage instance and you can set them as illustratedin the above example

Warning For the reason of backward compatibility FileBrowser settings FILEBROWSER_MEDIA_ROOT andFILEBROWSER_MEDIA_URL can still be used to customize FileBrowser as long as yoursquore using the defaultFileBrowserlsquos site without having changed its storage engine In the next major release of FileBrowser thesesettings will be removed

StorageMixin Class

A FileBrowser uses the Djangorsquos Storage class to access media files However the API of the Storageclass does not provide all methods necessary for FileBrowserrsquos functionality A StorageMixin class fromfilebrowserstorage module therefore defines all the additional methods that a FileBrowser requires

isdir(self name)Returns true if name exists and is a directory

41 Admin Interface 25

Django FileBrowser Documentation Release 357

isfile(self name)Returns true if name exists and is a regular file

move(self old_file_name new_file_name allow_overwrite=False)Moves safely a file from one location to another If allow_ovewrite==False and new_file_nameexists raises an exception

makedirs(self name)Creates all missing directories specified by name Analogue to osmkdirs()

414 Views

All views use the staff_member_requird and path_exists decorator in order to check if the server pathactually exists Some views also use the file_exists decorator

bull Browse fb_browse Browse a directory on your server Returns a FileListing

ndash Optional query string args dir o ot q p filter_date filter_type type

bull Create directory fb_createdir Create a new folder on your server

ndash Optional query string args dir

ndash Signals filebrowser_pre_createdir filebrowser_post_createdir

bull Upload fb_upload Multiple upload

ndash Optional query string args dir type

ndash Signals filebrowser_pre_upload filebrowser_post_upload

bull Edit fb_edit Edit a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_rename filebrowser_post_rename

You are able to apply custom actions (see Custom Actions) to the edit-view

bull Confirm delete fb_confirm_delete Confirm the deletion of a file or folder

ndash Required query string args filename

ndash Optional query string args dir

If you try to delete a folder all filesfolders within this folder are listed on this page

bull Delete fb_delete Delete a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_delete filebrowser_post_delete

Warning If you delete a Folder all items within this Folder are being deleted

bull Version fb_version Generate a version of an image as defined with ADMIN_VERSIONS

ndash Required query string args filename

ndash Optional Query string args dir

This is a helper used by the FileBrowseField and TinyMCE for selecting a version

26 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

415 Signals

The FileBrowser sends a couple of different signals Please take a look at the module filebrowsersignals for furtherexplanation on the provided arguments

bull filebrowser_pre_upload Sent before a an Upload starts

bull filebrowser_post_upload Sent after an Upload has finished

bull filebrowser_pre_delete Sent before an Item (File Folder) is deleted

bull filebrowser_post_delete Sent after an Item (File Folder) has been deleted

bull filebrowser_pre_createdir Sent before a new Folder is created

bull filebrowser_post_createdir Sent after a new Folder has been created

bull filebrowser_pre_rename Sent before an Item (File Folder) is renamed

bull filebrowser_post_rename Sent after an Item (File Folder) has been renamed

bull filebrowser_actions_pre_apply Sent before a custom action is applied

bull filebrowser_actions_post_apply Sent after a custom action has been applied

Example for using these Signals

Herersquos a small example for using the above Signals

from filebrowser import signals

def pre_upload_callback(sender kwargs)Receiver function called before an upload startsprint Pre Upload Callbackprint kwargs kwargs

signalsfilebrowser_pre_uploadconnect(pre_upload_callback)

def post_upload_callback(sender kwargs)Receiver function called each time an upload has finishedprint Post Upload Callbackprint kwargs kwargs You can use all attributes available with the FileObject This is just an example print Filesize kwargs[file]filesizeprint Orientation kwargs[file]orientationprint Extension kwargs[file]extension

signalsfilebrowser_post_uploadconnect(post_upload_callback)

41 Admin Interface 27

Django FileBrowser Documentation Release 357

28 Chapter 4 Admin Interface

CHAPTER 5

Image Versions

51 Versions

With the FileBrowser you are able to define different versionssizes for images This enables you to save an originalimage on your server while having different versions of that image to automatically fit your websites grid Versionsare also useful for responsiveadaptive layouts

511 Defining Versions

New in version 340 methods

First you need to know which versionssizes of an image yoursquod like to generate with your website Letrsquos say yoursquoreusing a 12 column grid with 60px for each column and 20px margin (which is a total of 940px) With this grid youcould (for example) define these image versions

FILEBROWSER_VERSIONS_BASEDIR = _versionsFILEBROWSER_VERSIONS =

admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

Use the methods argument if you need to add a filter

def grayscale(im)Convert image to grayscaleif immode = L

im = imconvert(L)return im

FILEBROWSER_VERSIONS = big verbose_name Big (6 col) width 460 height opts methods [grayscale]

)

29

Django FileBrowser Documentation Release 357

512 Versions and the Admin

When using the FileBrowser with the admin interface you need to define ADMIN_VERSIONS andADMIN_THUMBNAIL (see Settings) ADMIN_VERSIONS are available with the admin ie you are able to seethese versions with the image detail view and you are able to select the versions with the FileBrowseField model field

FILEBROWSER_ADMIN_VERSIONS = [thumbnail small medium big large]FILEBROWSER_ADMIN_THUMBNAIL = admin_thumbnail

513 Versions and the Frontend

With your templates you have two different tags to choose from version and version_object With bothtags the version will be generated if it doesnrsquot already exist OR if the original image is newer than the version Inorder to update an image you just overwrite the original image and the versions will be generated automatically (asyou request them within your template)

A Model example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 blank=True null=True)

With your templates use version if you simply need to retrieve the URL or version_object if you need to geta FileObject

lt-- load filebrowser templatetags --gt load fb_versions

lt-- get the url with version --gtltimg src= version blogentryimage medium gt

lt-- get a fileobject with version_object --gt version_object blogentryimage medium as version_medium version_mediumwidth ltimg src= version_medium gt

Templatetag version

RetrievesGenerates a version and returns an URL

version modelfield_name version_prefix

Templatetag version_object

RetrievesGenerates a version and returns a FileObject

version_object modelfield_name version_prefix as variable

Note With both templatetags version_prefix can either be a string or a variable If version_prefix is astring use quotes

30 Chapter 5 Image Versions

Django FileBrowser Documentation Release 357

514 Versions in Views

If you have a FileObject you can generateretrieve a version with

v = objimageversion_generate(version_prefix) returns a FileObject

515 Placeholder

When developing on a locale machine or a development-server you might not have all the images (resp media-files)available that are on your production instance and downloading these files on a regular basis might not be an option

In that case you can use a placeholder instead of a version You just need to define the PLACEHOLDER and overwritethe settings SHOW_PLACEHOLDER andor FORCE_PLACEHOLDER (see Placeholder)

516 Management Commands

fb_version_generateIf you need to generate certain (or all) versions type

python managepy fb_version_generate

fb_version_removeIf you need to generate certain (or all) versions type

python managepy fb_version_generate

Warning Please be very careful with this command

51 Versions 31

Django FileBrowser Documentation Release 357

32 Chapter 5 Image Versions

CHAPTER 6

Help

61 Help

611 FAQ

Why should I use the FileBrowser

If you need your editors or customers to manage files the FileBrowser is an alternative to an FTP-client Moreoveryou are able to define different image versions according to your websites grid Alternatives to the FileBrowser can befound at httpdjangopackagescomgridsgfile-managers

Do I need Grappelli

Grappelli is a requirement for using the FileBrowser There are several filebrowser-no-grappelli repositories (most ofthem on GitHub) but we donrsquot follow the development

I need help

see Troubleshooting

Why are there no fancy effects

The FileBrowser is about managing files We think that you should prepare your files before uploading them to theserver

How do I upload to another server

Use a custom storage engine see httpsdocsdjangoprojectcomen16howtocustom-file-storage

Why do I need image-versions

You need image-versions if your website is based on a grid

33

Django FileBrowser Documentation Release 357

Is the FileBrowser stable

Wersquove developed the FileBrowser for a couple of years and use it with almost all of our clients That said Grappelli isthe more stable and mature application

How can I contribute

Help is very much needed and appreciated Test the FileBrowser and submit feedbackpatches

Who develops the FileBrowser

The FileBrowser is developed and maintained by Patrick Kranzlmuumlller amp Axel Swoboda of vonautomatisch

612 Troubleshooting

Check your setup

Please check if the problem is caused by your setup

bull Read Quick start guide

bull Check if the staticmedia-files are served correctly

bull Make sure you have removed all custom FileBrowser templates from all locations in TEMPLATE_DIRS orcheck that these templates are compatible with the FileBrowser

Run the tests

Start the shell and type

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Check issues

If your setup is fine please check if your problem is a known issue

bull Take a look at all FileBrowser Issues (incuding closed) and search the FileBrowser Google-Group

Add a ticket

If you think yoursquove found a bug please add a ticket

bull Try to describe your problem as precisely as possible

bull Tell us what you did in order to solve the problem

bull Tell us what version of the FileBrowser you are using

bull Tell us what version of Django you are using

34 Chapter 6 Help

Django FileBrowser Documentation Release 357

bull Please do NOT add tickets if yoursquore having problems with serving staticmedia-files (because this is not relatedto the FileBrowser)

bull Please do NOT add tickets referring to Djangos trunk version

bull At best add a patch

Note Be aware that we may close issues not following these guidlines without further notifications

613 Translation

Translation is done via Transifex

Supported Languages

see httpswwwtransifexnetprojectspdjango-filebrowserresourcedjangopo

614 FileBrowser 35 Release Notes

FileBrowser 35 is compatible with Django 14151617 as well as Grappelli 242526

Update from FileBrowser 34x

bull Update Django to 14151617 and check httpsdocsdjangoprojectcomendevreleases14 orhttpsdocsdjangoprojectcomendevreleases15 or httpsdocsdjangoprojectcomendevreleases16

bull Update Grappelli to 24x25x26x

bull Update FileBrowser to 35x

62 Changelog

621 358 (not yet released)

622 357 (September 10th 2014)

bull New Compatibility with Django 17 and Grappelli 26x

bull Improved Updated tests because of the new random suffix with get_available_name (django storage)

bull Improved Added an icon in order to mark finished uploads

bull Improved Show resulting filename (eg with suffix converted) after successful upload

bull Fixed Permissions with file upload

bull Fixed Unified json response with _upload_file (no matter if file already exists or not)

623 356 (April 16th 2014)

bull Fixed Displaying pagination correctly with lots of entries

62 Changelog 35

Django FileBrowser Documentation Release 357

624 355 (April 13th 2014)

bull New Added client-side (JavaScript) file extension validation to the AJAX uploader

bull New Added experimental Python 33 support

bull Improved Tests with convertnormalize (removed special chars from test filename)

bull Fixed File selection after using search box (CKEditor)

bull Fixed Removed encoding of file URIs with CKEditor

625 354 (February 21st 2014)

bull Fixed Placeholder functionality (including tests)

bull Fixed Convertnormalize filenames (including tests)

bull Fixed Handling uppercase extensions with browse

626 353 (January 7 2014)

bull New added path_full to FileObject

bull Improved added docx to EXTENSIONS

bull Improved Recommend pillow instead of PIL as a requirement

bull Improved Added additional test cases

bull Improved Updated documentation

bull Improved Consistent use of storage (eg storagelocation storageurl)

bull Improved Removed unnecessary functions (eg url_join url_strip)

bull Improved Moved sort_by_attr to FileListing

bull Improved Regex matches with file versions on browse

bull Improved Using djangoconfurls (with djangoconfurlsdefaults as fallback)

bull Improved Adding CONTRIBUTINGrst

bull Improved Removed static Media inner class with fields

bull Improved Removed search icon with fields (has not being used)

bull Improved Added custom class attributes with filebrowser field

bull Improved Updated translations

bull Fixed fixed exception handling with python 25

bull Fixed fixes dir with SEARCH_TRAVERSE true and version select

bull Fixed Make Django FileUploadHandlers work (also fixed a memory leak)

bull Fixed return correct filename with OVERWRITE_EXISTING

bull Fixed fb_version_generate with FILEBROWSER_VERSIONS_BASEDIR

bull Fixed Table sorting with ascdesc

bull Fixed Added DeprecationWarning for FileObjectdirectory and FileObjectfolder

36 Chapter 6 Help

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

Django FileBrowser Documentation Release 357

MAX_UPLOAD_SIZE

Max Upload Size in Bytes

MAX_UPLOAD_SIZE = getattr(settings FILEBROWSER_MAX_UPLOAD_SIZE 10485760)

NORMALIZE_FILENAME

True if you want to normalize filename on upload and remove all non-alphanumeric characters (except for under-scores spaces amp dashes)

NORMALIZE_FILENAME = getattr(settings FILEBROWSER_NORMALIZE_FILENAME False)

CONVERT_FILENAME

True if you want to convert the filename on upload (replace spaces and convert to lowercase)

CONVERT_FILENAME = getattr(settings FILEBROWSER_CONVERT_FILENAME True)

LIST_PER_PAGE

How many items appear on each paginated list

LIST_PER_PAGE = getattr(settings FILEBROWSER_LIST_PER_PAGE 50)

DEFAULT_SORTING_BY

Default sorting attribute

DEFAULT_SORTING_BY = getattr(settings FILEBROWSER_DEFAULT_SORTING_BY date)

Options are date filesize filename_lower filetype_checked

DEFAULT_SORTING_ORDER

Default sorting order

DEFAULT_SORTING_ORDER = getattr(settings FILEBROWSER_DEFAULT_SORTING_ORDER desc)

Options are asc or desc

FOLDER_REGEX

regex to clean directory names before creation

FOLDER_REGEX = getattr(settings FILEBROWSER_FOLDER_REGEX r^[w_ -]+$)

8 Chapter 1 Installation and Setup

Django FileBrowser Documentation Release 357

SEARCH_TRAVERSE

True if you want to traverse all subdirectories when searching Please note that with thousands of filesdirectoriesthis might take a while

SEARCH_TRAVERSE = getattr(settings FILEBROWSER_SEARCH_TRAVERSE False)

DEFAULT_PERMISSIONS

Default upload and version permissions

DEFAULT_PERMISSIONS = getattr(settings FILEBROWSER_DEFAULT_PERMISSIONS 0755)

OVERWRITE_EXISTING

New in version 351

True in order to overwrite existing files False to use the behaviour of the storage engine

OVERWRITE_EXISTING = getattr(settings FILEBROWSER_OVERWRITE_EXISTING True)

12 Settings 9

Django FileBrowser Documentation Release 357

10 Chapter 1 Installation and Setup

CHAPTER 2

API

21 API

211 FileListing

class FileListing(path filter_func=None sorting_by=None sorting_order=None)Returns a list of FileObjects for a server path see FileObject

Parameters

bull path ndash Relative path to a location within sitestoragelocation

bull filter_func ndash Filter function see example below

bull sorting_by ndash Sort the files by any attribute of FileObject

bull sorting_order ndash Sorting order either ldquoascrdquo or ldquodescrdquo

If you want to list all files within a storage location you do

from filebrowsersites import sitefrom filebrowserbase import FileListingfilelisting = FileListing(sitestoragelocation sorting_by=date sorting_order=desc)

Use a custom filter function to limit the list of files

def filter_filelisting(item) item is a FileObjectreturn itemfiletype = Folder

filelisting = FileListing(sitestoragelocation filter_func=filter_listing sorting_by=date sorting_order=desc)

Methods

For the below examples wersquore using this folder-structure

mediauploadstestfoldertestimagejpgmediauploadsblog1imagesblogimagejpg

Note We defined filter_browse as filter_func (see sitespy) And we did not define aVERSIONS_BASEDIR for this demonstration though it is highly recommended to use one

11

Django FileBrowser Documentation Release 357

listing()Returns all items for the given path with oslistdir(path)

gtgtgt for item in filelistinglisting() print itemblogtestfolder

walk()Returns all items for the given path with oswalk(path)

gtgtgt for item in filelistingwalk() print itemblogblog1blog1imagesblog1imagesblogimagejpgblog1imagesblogimage_admin_thumbnailjpgblog1imagesblogimage_mediumjpgblog1imagesblogimage_smalljpgblog1imagesblogimage_thumbnailjpgtestfoldertestfoldertestimagejpg

files_listing_total()Returns a sorted list of FileObjects for listing()

gtgtgt for item in filelistingfiles_listing_total() print itemuploadsbloguploadstestfolder

files_walk_total()Returns a sorted list of FileObjects for walk()

gtgtgt for item in filelistingfiles_walk_total() print itemuploadsbloguploadsblog1uploadsblog1imagesuploadsblog1imagesblogimagejpguploadsblog1imagesblogimage_admin_thumbnailjpguploadsblog1imagesblogimage_mediumjpguploadsblog1imagesblogimage_smalljpguploadsblog1imagesblogimage_thumbnailjpguploadstestfolderuploadstestfoldertestimagejpg

files_listing_filtered()Returns a sorted and filtered list of FileObjects for listing()

gtgtgt for item in filelistingfiles_listing_filtered() print itemuploadsbloguploadstestfolder

files_walk_filtered()Returns a sorted and filtered list of FileObjects for walk()

12 Chapter 2 API

Django FileBrowser Documentation Release 357

gtgtgt for item in filelistingfiles_walk_filtered() print itemuploadsbloguploadsblog1uploadsblog1imagesuploadsblog1imagesblogimagejpguploadstestfolderuploadstestfoldertestimagejpg

Note The versions are not listed (compared with files_walk_total) because of filter_func

results_listing_total()Number of total files based on files_listing_total()

gtgtgt filelistingresults_listing_total()2

results_walk_total()Number of total files based on files_walk_total()

gtgtgt filelistingresults_walk_total()10

results_listing_filtered()Number of filtered files based on files_listing_filtered()

gtgtgt filelistingresults_listing_filtered()2

results_walk_filtered()Number of filtered files based on files_walk_filtered()

gtgtgt filelistingresults_walk_filtered()6

212 FileObject

class FileObject(path site=None)An object representing a media file

Parameters

bull path ndash Relative path to a location within sitestoragelocation

bull site ndash An optional FileBrowser Site

For example

from filebrowsersites import sitefrom filebrowserbase import FileObjectfileobject = FileObject(ospathjoin(sitedirectorytestfoldertestimagejpg))version = FileObject(ospathjoin(fileobjectversions_basedir testfolder testimage_mediumjpg))

21 API 13

Django FileBrowser Documentation Release 357

Attributes

Initial Attributes

pathPath relative to a storage location (including sitedirectory)

gtgtgt fileobjectpathuploadstestfoldertestimagejpg

headThe directory name of pathname path

gtgtgt fileobjectheaduploadstestfolder

filenameName of the file (including the extension) or name of the folder

gtgtgt fileobjectfilenametestimagejpg

filename_lowerLower type of filename

filename_rootFilename without extension

gtgtgt fileobjectfilename_roottestimage

extensionFile extension including the dot With a folder the extensions is None

gtgtgt fileobjectextensionjpg

mimetypeMimetype based on httpdocspythonorglibrarymimetypeshtml

gtgtgt fileobjectmimetype(imagejpeg None)

General Attributes

filetypeType of the file as defined with EXTENSIONS

gtgtgt fileobjectfiletypeImage

filesizeFilesize in Bytes

gtgtgt fileobjectfilesize870037L

14 Chapter 2 API

Django FileBrowser Documentation Release 357

dateDate based on timemktime

gtgtgt fileobjectdate12997603470

datetimeDatetime object

gtgtgt fileobjectdatetimedatetimedatetime(2011 3 10 13 32 27)

existsTrue if the path exists False otherwise

gtgtgt fileobjectexistsTrue

Path and URL attributes

pathPath relative to a storage location (including sitedirectory)

gtgtgt fileobjectpathuploadstestfoldertestimagejpg

path_relative_directoryPath relative to sitedirectory

gtgtgt fileobjectpath_relative_directorytestfoldertestimagejpg

path_fullAbsolute server path (based on storagepath)

gtgtgt fileobjectpath_fullabsolutepathtoserverlocationtestfoldertestimagejpg

dirnameNew in version 34

The directory (not including sitedirectory)

gtgtgt fileobjectdirnametestfolder

urlURL for the filefolder (based on storageurl)

gtgtgt fileobjecturlmediauploadstestfoldertestimagejpg

Image attributes

The image attributes are only useful if the FileObject represents an image

dimensionsImage dimensions as a tuple

21 API 15

Django FileBrowser Documentation Release 357

gtgtgt fileobjectdimensions(1000 750)

widthImage width in px

gtgtgt fileobjectwidth1000

heightImage height in px

gtgtgt fileobjectheight750

aspectratioAspect ratio (float format)

gtgtgt fileobjectaspectratio133534908

orientationImage orientation either Landscape or Portrait

gtgtgt fileobjectorientationLandscape

Folder attributes

The folder attributes make sense when the FileObject represents a directory (not a file)

directory

Deprecated since version 353 Use path_relative_directory instead

folder

Deprecated since version 353 Use dirname instead

is_folderTrue if path is a folder

gtgtgt fileobjectis_folderFalse

is_emptyTrue if the folder is empty False if the folder is not empty or the FileObject is not a folder

gtgtgt fileobjectis_emptyFalse

Version attributes

is_versiontrue if the File is a version of another File

16 Chapter 2 API

Django FileBrowser Documentation Release 357

gtgtgt fileobjectis_versionFalsegtgtgt versionis_versionTrue

versions_basedirThe relative path (from storage location) to the main versions folder Either VERSIONS_BASEDIR orsitedirectory

gtgtgt fileobjectversions_basedir_versionsgtgtgt versionversions_basedir_versions

originalReturns the original FileObject

gtgtgt fileobjectoriginalltFileObject uploadstestfoldertestimagejpggtgtgtgt versionoriginalltFileObject uploadstestfoldertestimagejpggt

original_filenameGet the filename of an original image from a version

gtgtgt fileobjectoriginal_filenametestimagejpggtgtgt versionoriginal_filenametestimagejpg

Methods

Version methods

versions()List all filenames based on VERSIONS

gtgtgt fileobjectversions()[_versionstestfoldertestimage_admin_thumbnailjpg_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionversions()[]

Note The versions are not being generated

admin_versions()List all filenames based on ADMIN_VERSIONS

gtgtgt fileobjectadmin_versions()[_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg

21 API 17

Django FileBrowser Documentation Release 357

_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionadmin_versions()[]

Note The versions are not being generated

version_name(version_suffix)Get the filename for a version

gtgtgt fileobjectversion_name(medium)testimage_mediumjpg

Note The version is not being generated

version_path(version_suffix)Get the path for a version

gtgtgt fileobjectversion_path(medium)_versionstestfoldertestimage_mediumjpg

Note The version is not being generated

version_generate(version_suffix)Generate a version

gtgtgt fileobjectversion_generate(medium)ltFileObject uploadstestfoldertestimage_mediumjpggt

Please note that a version is only generated if it does not already exist or if the original image is newer than theexisting version

Delete methods

delete()Delete the File or Folder from the server

Warning If you delete a Folder all items within the folder are being deleted

delete_versions()Delete all VERSIONS

delete_admin_versions()Delete all ADMIN_VERSIONS

18 Chapter 2 API

CHAPTER 3

Fields amp Widgets

31 Fields amp Widgets

The FileBrowseField is a custom model field which returns a FileObject The widgets FileInput and ClearableFileIn-put are used with the admin app in order to show an additional thumbnail for images

311 FileBrowseField

class FileBrowseField(max_length[ site directory extensions format options])A subclass of CharField referencing a media file within Returns a FileObject

Parameters

bull site ndash A FileBrowser site (defaults to the main site) see FileBrowser Site

bull directory ndash Directory to browse when clicking the search icon

bull extensions ndash List of allowed extensions see Extensions and Formats

bull format ndash A key from SELECT_FORMATS in order to restrict the selection to specificfiletypes see Extensions and Formats

For example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 directory=images extensions=[jpg] blank=True null=True)document = FileBrowseField(PDF max_length=200 directory=documents extensions=[pdfdoc] blank=True null=True)

FileBrowseField in Templates

You can use all attributes from FileObject

blogentryimage ltimg src= publicationimageurl gt

ifequal blogentryimageimage_orientation landscape ltimg src= blogentryimageurl class=landscape gt

endifequal

19

Django FileBrowser Documentation Release 357

Showing Thumbnail in the Changelist

To show a thumbnail with the changelist you can define a ModelAdmin method

from filebrowsersettings import ADMIN_THUMBNAIL

def image_thumbnail(self obj)if objimage and objimagefiletype == Image

return ltimg src=s gt objimageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Using the FileBrowseField with TinyMCE

In order to replace the TinyMCE imagefile manager with the FileBrowser you have to use a FileBrowser CallbackTherersquos an example TinyMCE configuration file in staticjs called TinyMCEAdminjs You can either copy theFileBrowserCallback to your own file or just use tinymce_setupjs (which comes with django-grappelli)

Just add these lines to your ModelAdmin asset definitions

class Mediajs = [pathtotinymcejscriptstiny_mcetiny_mcejs

pathtoyourtinymce_setupjs]

312 FileInput

Subclass of FileInput with an additional thumbnail

from filebrowserwidgets import FileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget FileInput

313 ClearableFileInput

Subclass of ClearableFileInput with an additional thumbnail

from filebrowserwidgets import ClearableFileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget ClearableFileInput

314 Django FileField and the FileBrowser

Return a FileObject from a FileField or ImageField with

20 Chapter 3 Fields amp Widgets

Django FileBrowser Documentation Release 357

from filebrowserbase import FileObject

image_upload = modelsImageField(uImage (Upload) max_length=250 upload_to=image_upload_path blank=True null=True)

def image(self)if selfimage_upload

return FileObject(selfimage_uploadpath)return None

In order show a thumbnail with your changelist you could use a ModelAdmin method

from filebrowserbase import FileObject

def image_thumbnail(self obj)if objimage_upload

image = FileObject(objimage_uploadpath)if imagefiletype == Image

return ltimg src=s gt imageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Note There are different ways to achieve this The above examples show one of several options

31 Fields amp Widgets 21

Django FileBrowser Documentation Release 357

22 Chapter 3 Fields amp Widgets

CHAPTER 4

Admin Interface

41 Admin Interface

The main FileBrowser admin application is an extension for the Django admin interface in order to browser yourmedia folder upload and renamedelete files

411 FileBrowser Site

New in version 340

class FileBrowserSite(name=None app_name=rsquofilebrowserrsquo storage=default_storage)Respresents the FileBrowser admin application (similar to Djangorsquos admin site)

Parameters

bull name ndash A name for the site defaults to None

bull app_name ndash Defaults to lsquofilebrowserrsquo

bull storage ndash A custom storage engine defaults to Djangos default storage

Similar to djangocontribadmin you first need to add a filebrowsersite to your admin interface Inyour urlspy import the default FileBrowser site (or your custom site) and add the site to your URL-patterns (beforeany admin-urls)

from filebrowsersites import site

urlpatterns = patterns(url(r^adminurlfilebrowser include(siteurls))

)

Now you are able to browse the location defined with the storage engine associated to your site

from djangocorefilesstorage import DefaultStoragefrom filebrowsersites import FileBrowserSite

Default FileBrowser sitesite = FileBrowserSite(name=filebrowser storage=DefaultStorage())

My Custom FileBrowser sitecustom_site = FileBrowserSite(name=custom_filebrowser storage=DefaultStorage())custom_sitedirectory = custom_uploads

23

Django FileBrowser Documentation Release 357

Note The module variable site from filebrowsersites is the default FileBrowser application

412 Custom Actions

New in version 340

Similar to Djangorsquos admin actions you can define your FileBrowser actions and thus automate the typical tasks ofyour users Registered custom actions are listed in the detail view of a file and a user can select a single action at atime The selected action will then be applied to the file

The default FileBrowser image actions such as ldquoFlip Verticalrdquo or ldquoRotate 90deg Clockwiserdquo are in fact implemented ascustom actions (see the module filebrowseractions)

Writing Your Own Actions

Custom actions are simple functions

def foo(request fileobjects) Do something with the fileobjects

The first parameter is a HttpRequest object (representing the submitted form in which a user selected the action)and the second parameter is a list of FileObjects to which the action should be applied

The list contains exactly one instance of FileObject (representing the file from the detail view) but this may change inthe future as custom actions may become available also in browse views (similar to admin actions applied to a list ofchecked objects)

Registering an Action

In order to make your action visible you need to register it with a FileBrowser site

siteadd_action(foo)

Once registered the action will appear in the detail view of a file You can also give your action a short description

fooshort_description = Do foo with the File

This short description will then appear in the list of available actions If you do not provide a short description thefunction name will be used instead and FileBrowser will replace any underscores in the function name with spaces

Associating Actions with Specific Files

Each custom action can be associated with a specific file type (eg images audio file etc) to which it applies In orderto do that you need to define a predicatefilter function which takes a single argument (FileObject) and returns Trueif your action is applicable to that FileObject Finally you need to register this filter function with your action

fooapplies_to(lambda fileobject fileobjectfiletype == Image)

In the above example foo will appear in the action list only for image files If you do not specify any filter functionfor your action FileBrowser considers the action as applicable to all files

24 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

Messages amp Intermediate Pages

You can provide a feedback to a user about a successful or failed execution of an action by using a message Forexample

from djangocontrib import messages

def desaturate_image(request fileobjects)for f in fileobjects

Desaturate the imagemessagesadd_message(request messagesSUCCESS _(Image s was desaturated) ffilename)

Some actions may require user confirmation (eg in order to prevent accidental and irreversible modification tofiles) In order to that follow the same pattern as with Djangorsquos admin action and return a HttpResponse objectfrom your action Good practice for intermediate pages is to implement a confirm view and have your action returnHttpResponseRedirect

def crop_image(request fileobjects)files = ampf=join([fpath_relative for f in fileobjects])return HttpResponseRedirect(confirmaction=crop_imageampf=s files)

413 File Storages

New in version 340

You have the option to specify which file storage engine a FileBrowser should use to browseuploadmodify yourmedia files This enables you to use a FileBrowser even if your media files are located at some remote system Seealso the Djangorsquos documentation on storages httpsdocsdjangoprojectcomendevtopicsfiles

To associate a FileBrowser site with a particular storage engine set the storage property of a site object

from djangocorefilesstorage import FileSystemStoragesitestorage = FileSystemStorage(location=pathtomediadirectory base_url=media)

For storage classes other than FileSystemStorage (or those that inherit from that class) therersquos more effort involved inproviding a storage object that can be used with FileBrowser See StorageMixin Class

Note Prior FileBrowser 34 the way to specify FileBrowserlsquos MEDIA_ROOT and MEDIA_URL was via settingspyStarting from version 34 those variables are associated with the storage instance and you can set them as illustratedin the above example

Warning For the reason of backward compatibility FileBrowser settings FILEBROWSER_MEDIA_ROOT andFILEBROWSER_MEDIA_URL can still be used to customize FileBrowser as long as yoursquore using the defaultFileBrowserlsquos site without having changed its storage engine In the next major release of FileBrowser thesesettings will be removed

StorageMixin Class

A FileBrowser uses the Djangorsquos Storage class to access media files However the API of the Storageclass does not provide all methods necessary for FileBrowserrsquos functionality A StorageMixin class fromfilebrowserstorage module therefore defines all the additional methods that a FileBrowser requires

isdir(self name)Returns true if name exists and is a directory

41 Admin Interface 25

Django FileBrowser Documentation Release 357

isfile(self name)Returns true if name exists and is a regular file

move(self old_file_name new_file_name allow_overwrite=False)Moves safely a file from one location to another If allow_ovewrite==False and new_file_nameexists raises an exception

makedirs(self name)Creates all missing directories specified by name Analogue to osmkdirs()

414 Views

All views use the staff_member_requird and path_exists decorator in order to check if the server pathactually exists Some views also use the file_exists decorator

bull Browse fb_browse Browse a directory on your server Returns a FileListing

ndash Optional query string args dir o ot q p filter_date filter_type type

bull Create directory fb_createdir Create a new folder on your server

ndash Optional query string args dir

ndash Signals filebrowser_pre_createdir filebrowser_post_createdir

bull Upload fb_upload Multiple upload

ndash Optional query string args dir type

ndash Signals filebrowser_pre_upload filebrowser_post_upload

bull Edit fb_edit Edit a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_rename filebrowser_post_rename

You are able to apply custom actions (see Custom Actions) to the edit-view

bull Confirm delete fb_confirm_delete Confirm the deletion of a file or folder

ndash Required query string args filename

ndash Optional query string args dir

If you try to delete a folder all filesfolders within this folder are listed on this page

bull Delete fb_delete Delete a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_delete filebrowser_post_delete

Warning If you delete a Folder all items within this Folder are being deleted

bull Version fb_version Generate a version of an image as defined with ADMIN_VERSIONS

ndash Required query string args filename

ndash Optional Query string args dir

This is a helper used by the FileBrowseField and TinyMCE for selecting a version

26 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

415 Signals

The FileBrowser sends a couple of different signals Please take a look at the module filebrowsersignals for furtherexplanation on the provided arguments

bull filebrowser_pre_upload Sent before a an Upload starts

bull filebrowser_post_upload Sent after an Upload has finished

bull filebrowser_pre_delete Sent before an Item (File Folder) is deleted

bull filebrowser_post_delete Sent after an Item (File Folder) has been deleted

bull filebrowser_pre_createdir Sent before a new Folder is created

bull filebrowser_post_createdir Sent after a new Folder has been created

bull filebrowser_pre_rename Sent before an Item (File Folder) is renamed

bull filebrowser_post_rename Sent after an Item (File Folder) has been renamed

bull filebrowser_actions_pre_apply Sent before a custom action is applied

bull filebrowser_actions_post_apply Sent after a custom action has been applied

Example for using these Signals

Herersquos a small example for using the above Signals

from filebrowser import signals

def pre_upload_callback(sender kwargs)Receiver function called before an upload startsprint Pre Upload Callbackprint kwargs kwargs

signalsfilebrowser_pre_uploadconnect(pre_upload_callback)

def post_upload_callback(sender kwargs)Receiver function called each time an upload has finishedprint Post Upload Callbackprint kwargs kwargs You can use all attributes available with the FileObject This is just an example print Filesize kwargs[file]filesizeprint Orientation kwargs[file]orientationprint Extension kwargs[file]extension

signalsfilebrowser_post_uploadconnect(post_upload_callback)

41 Admin Interface 27

Django FileBrowser Documentation Release 357

28 Chapter 4 Admin Interface

CHAPTER 5

Image Versions

51 Versions

With the FileBrowser you are able to define different versionssizes for images This enables you to save an originalimage on your server while having different versions of that image to automatically fit your websites grid Versionsare also useful for responsiveadaptive layouts

511 Defining Versions

New in version 340 methods

First you need to know which versionssizes of an image yoursquod like to generate with your website Letrsquos say yoursquoreusing a 12 column grid with 60px for each column and 20px margin (which is a total of 940px) With this grid youcould (for example) define these image versions

FILEBROWSER_VERSIONS_BASEDIR = _versionsFILEBROWSER_VERSIONS =

admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

Use the methods argument if you need to add a filter

def grayscale(im)Convert image to grayscaleif immode = L

im = imconvert(L)return im

FILEBROWSER_VERSIONS = big verbose_name Big (6 col) width 460 height opts methods [grayscale]

)

29

Django FileBrowser Documentation Release 357

512 Versions and the Admin

When using the FileBrowser with the admin interface you need to define ADMIN_VERSIONS andADMIN_THUMBNAIL (see Settings) ADMIN_VERSIONS are available with the admin ie you are able to seethese versions with the image detail view and you are able to select the versions with the FileBrowseField model field

FILEBROWSER_ADMIN_VERSIONS = [thumbnail small medium big large]FILEBROWSER_ADMIN_THUMBNAIL = admin_thumbnail

513 Versions and the Frontend

With your templates you have two different tags to choose from version and version_object With bothtags the version will be generated if it doesnrsquot already exist OR if the original image is newer than the version Inorder to update an image you just overwrite the original image and the versions will be generated automatically (asyou request them within your template)

A Model example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 blank=True null=True)

With your templates use version if you simply need to retrieve the URL or version_object if you need to geta FileObject

lt-- load filebrowser templatetags --gt load fb_versions

lt-- get the url with version --gtltimg src= version blogentryimage medium gt

lt-- get a fileobject with version_object --gt version_object blogentryimage medium as version_medium version_mediumwidth ltimg src= version_medium gt

Templatetag version

RetrievesGenerates a version and returns an URL

version modelfield_name version_prefix

Templatetag version_object

RetrievesGenerates a version and returns a FileObject

version_object modelfield_name version_prefix as variable

Note With both templatetags version_prefix can either be a string or a variable If version_prefix is astring use quotes

30 Chapter 5 Image Versions

Django FileBrowser Documentation Release 357

514 Versions in Views

If you have a FileObject you can generateretrieve a version with

v = objimageversion_generate(version_prefix) returns a FileObject

515 Placeholder

When developing on a locale machine or a development-server you might not have all the images (resp media-files)available that are on your production instance and downloading these files on a regular basis might not be an option

In that case you can use a placeholder instead of a version You just need to define the PLACEHOLDER and overwritethe settings SHOW_PLACEHOLDER andor FORCE_PLACEHOLDER (see Placeholder)

516 Management Commands

fb_version_generateIf you need to generate certain (or all) versions type

python managepy fb_version_generate

fb_version_removeIf you need to generate certain (or all) versions type

python managepy fb_version_generate

Warning Please be very careful with this command

51 Versions 31

Django FileBrowser Documentation Release 357

32 Chapter 5 Image Versions

CHAPTER 6

Help

61 Help

611 FAQ

Why should I use the FileBrowser

If you need your editors or customers to manage files the FileBrowser is an alternative to an FTP-client Moreoveryou are able to define different image versions according to your websites grid Alternatives to the FileBrowser can befound at httpdjangopackagescomgridsgfile-managers

Do I need Grappelli

Grappelli is a requirement for using the FileBrowser There are several filebrowser-no-grappelli repositories (most ofthem on GitHub) but we donrsquot follow the development

I need help

see Troubleshooting

Why are there no fancy effects

The FileBrowser is about managing files We think that you should prepare your files before uploading them to theserver

How do I upload to another server

Use a custom storage engine see httpsdocsdjangoprojectcomen16howtocustom-file-storage

Why do I need image-versions

You need image-versions if your website is based on a grid

33

Django FileBrowser Documentation Release 357

Is the FileBrowser stable

Wersquove developed the FileBrowser for a couple of years and use it with almost all of our clients That said Grappelli isthe more stable and mature application

How can I contribute

Help is very much needed and appreciated Test the FileBrowser and submit feedbackpatches

Who develops the FileBrowser

The FileBrowser is developed and maintained by Patrick Kranzlmuumlller amp Axel Swoboda of vonautomatisch

612 Troubleshooting

Check your setup

Please check if the problem is caused by your setup

bull Read Quick start guide

bull Check if the staticmedia-files are served correctly

bull Make sure you have removed all custom FileBrowser templates from all locations in TEMPLATE_DIRS orcheck that these templates are compatible with the FileBrowser

Run the tests

Start the shell and type

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Check issues

If your setup is fine please check if your problem is a known issue

bull Take a look at all FileBrowser Issues (incuding closed) and search the FileBrowser Google-Group

Add a ticket

If you think yoursquove found a bug please add a ticket

bull Try to describe your problem as precisely as possible

bull Tell us what you did in order to solve the problem

bull Tell us what version of the FileBrowser you are using

bull Tell us what version of Django you are using

34 Chapter 6 Help

Django FileBrowser Documentation Release 357

bull Please do NOT add tickets if yoursquore having problems with serving staticmedia-files (because this is not relatedto the FileBrowser)

bull Please do NOT add tickets referring to Djangos trunk version

bull At best add a patch

Note Be aware that we may close issues not following these guidlines without further notifications

613 Translation

Translation is done via Transifex

Supported Languages

see httpswwwtransifexnetprojectspdjango-filebrowserresourcedjangopo

614 FileBrowser 35 Release Notes

FileBrowser 35 is compatible with Django 14151617 as well as Grappelli 242526

Update from FileBrowser 34x

bull Update Django to 14151617 and check httpsdocsdjangoprojectcomendevreleases14 orhttpsdocsdjangoprojectcomendevreleases15 or httpsdocsdjangoprojectcomendevreleases16

bull Update Grappelli to 24x25x26x

bull Update FileBrowser to 35x

62 Changelog

621 358 (not yet released)

622 357 (September 10th 2014)

bull New Compatibility with Django 17 and Grappelli 26x

bull Improved Updated tests because of the new random suffix with get_available_name (django storage)

bull Improved Added an icon in order to mark finished uploads

bull Improved Show resulting filename (eg with suffix converted) after successful upload

bull Fixed Permissions with file upload

bull Fixed Unified json response with _upload_file (no matter if file already exists or not)

623 356 (April 16th 2014)

bull Fixed Displaying pagination correctly with lots of entries

62 Changelog 35

Django FileBrowser Documentation Release 357

624 355 (April 13th 2014)

bull New Added client-side (JavaScript) file extension validation to the AJAX uploader

bull New Added experimental Python 33 support

bull Improved Tests with convertnormalize (removed special chars from test filename)

bull Fixed File selection after using search box (CKEditor)

bull Fixed Removed encoding of file URIs with CKEditor

625 354 (February 21st 2014)

bull Fixed Placeholder functionality (including tests)

bull Fixed Convertnormalize filenames (including tests)

bull Fixed Handling uppercase extensions with browse

626 353 (January 7 2014)

bull New added path_full to FileObject

bull Improved added docx to EXTENSIONS

bull Improved Recommend pillow instead of PIL as a requirement

bull Improved Added additional test cases

bull Improved Updated documentation

bull Improved Consistent use of storage (eg storagelocation storageurl)

bull Improved Removed unnecessary functions (eg url_join url_strip)

bull Improved Moved sort_by_attr to FileListing

bull Improved Regex matches with file versions on browse

bull Improved Using djangoconfurls (with djangoconfurlsdefaults as fallback)

bull Improved Adding CONTRIBUTINGrst

bull Improved Removed static Media inner class with fields

bull Improved Removed search icon with fields (has not being used)

bull Improved Added custom class attributes with filebrowser field

bull Improved Updated translations

bull Fixed fixed exception handling with python 25

bull Fixed fixes dir with SEARCH_TRAVERSE true and version select

bull Fixed Make Django FileUploadHandlers work (also fixed a memory leak)

bull Fixed return correct filename with OVERWRITE_EXISTING

bull Fixed fb_version_generate with FILEBROWSER_VERSIONS_BASEDIR

bull Fixed Table sorting with ascdesc

bull Fixed Added DeprecationWarning for FileObjectdirectory and FileObjectfolder

36 Chapter 6 Help

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

Django FileBrowser Documentation Release 357

SEARCH_TRAVERSE

True if you want to traverse all subdirectories when searching Please note that with thousands of filesdirectoriesthis might take a while

SEARCH_TRAVERSE = getattr(settings FILEBROWSER_SEARCH_TRAVERSE False)

DEFAULT_PERMISSIONS

Default upload and version permissions

DEFAULT_PERMISSIONS = getattr(settings FILEBROWSER_DEFAULT_PERMISSIONS 0755)

OVERWRITE_EXISTING

New in version 351

True in order to overwrite existing files False to use the behaviour of the storage engine

OVERWRITE_EXISTING = getattr(settings FILEBROWSER_OVERWRITE_EXISTING True)

12 Settings 9

Django FileBrowser Documentation Release 357

10 Chapter 1 Installation and Setup

CHAPTER 2

API

21 API

211 FileListing

class FileListing(path filter_func=None sorting_by=None sorting_order=None)Returns a list of FileObjects for a server path see FileObject

Parameters

bull path ndash Relative path to a location within sitestoragelocation

bull filter_func ndash Filter function see example below

bull sorting_by ndash Sort the files by any attribute of FileObject

bull sorting_order ndash Sorting order either ldquoascrdquo or ldquodescrdquo

If you want to list all files within a storage location you do

from filebrowsersites import sitefrom filebrowserbase import FileListingfilelisting = FileListing(sitestoragelocation sorting_by=date sorting_order=desc)

Use a custom filter function to limit the list of files

def filter_filelisting(item) item is a FileObjectreturn itemfiletype = Folder

filelisting = FileListing(sitestoragelocation filter_func=filter_listing sorting_by=date sorting_order=desc)

Methods

For the below examples wersquore using this folder-structure

mediauploadstestfoldertestimagejpgmediauploadsblog1imagesblogimagejpg

Note We defined filter_browse as filter_func (see sitespy) And we did not define aVERSIONS_BASEDIR for this demonstration though it is highly recommended to use one

11

Django FileBrowser Documentation Release 357

listing()Returns all items for the given path with oslistdir(path)

gtgtgt for item in filelistinglisting() print itemblogtestfolder

walk()Returns all items for the given path with oswalk(path)

gtgtgt for item in filelistingwalk() print itemblogblog1blog1imagesblog1imagesblogimagejpgblog1imagesblogimage_admin_thumbnailjpgblog1imagesblogimage_mediumjpgblog1imagesblogimage_smalljpgblog1imagesblogimage_thumbnailjpgtestfoldertestfoldertestimagejpg

files_listing_total()Returns a sorted list of FileObjects for listing()

gtgtgt for item in filelistingfiles_listing_total() print itemuploadsbloguploadstestfolder

files_walk_total()Returns a sorted list of FileObjects for walk()

gtgtgt for item in filelistingfiles_walk_total() print itemuploadsbloguploadsblog1uploadsblog1imagesuploadsblog1imagesblogimagejpguploadsblog1imagesblogimage_admin_thumbnailjpguploadsblog1imagesblogimage_mediumjpguploadsblog1imagesblogimage_smalljpguploadsblog1imagesblogimage_thumbnailjpguploadstestfolderuploadstestfoldertestimagejpg

files_listing_filtered()Returns a sorted and filtered list of FileObjects for listing()

gtgtgt for item in filelistingfiles_listing_filtered() print itemuploadsbloguploadstestfolder

files_walk_filtered()Returns a sorted and filtered list of FileObjects for walk()

12 Chapter 2 API

Django FileBrowser Documentation Release 357

gtgtgt for item in filelistingfiles_walk_filtered() print itemuploadsbloguploadsblog1uploadsblog1imagesuploadsblog1imagesblogimagejpguploadstestfolderuploadstestfoldertestimagejpg

Note The versions are not listed (compared with files_walk_total) because of filter_func

results_listing_total()Number of total files based on files_listing_total()

gtgtgt filelistingresults_listing_total()2

results_walk_total()Number of total files based on files_walk_total()

gtgtgt filelistingresults_walk_total()10

results_listing_filtered()Number of filtered files based on files_listing_filtered()

gtgtgt filelistingresults_listing_filtered()2

results_walk_filtered()Number of filtered files based on files_walk_filtered()

gtgtgt filelistingresults_walk_filtered()6

212 FileObject

class FileObject(path site=None)An object representing a media file

Parameters

bull path ndash Relative path to a location within sitestoragelocation

bull site ndash An optional FileBrowser Site

For example

from filebrowsersites import sitefrom filebrowserbase import FileObjectfileobject = FileObject(ospathjoin(sitedirectorytestfoldertestimagejpg))version = FileObject(ospathjoin(fileobjectversions_basedir testfolder testimage_mediumjpg))

21 API 13

Django FileBrowser Documentation Release 357

Attributes

Initial Attributes

pathPath relative to a storage location (including sitedirectory)

gtgtgt fileobjectpathuploadstestfoldertestimagejpg

headThe directory name of pathname path

gtgtgt fileobjectheaduploadstestfolder

filenameName of the file (including the extension) or name of the folder

gtgtgt fileobjectfilenametestimagejpg

filename_lowerLower type of filename

filename_rootFilename without extension

gtgtgt fileobjectfilename_roottestimage

extensionFile extension including the dot With a folder the extensions is None

gtgtgt fileobjectextensionjpg

mimetypeMimetype based on httpdocspythonorglibrarymimetypeshtml

gtgtgt fileobjectmimetype(imagejpeg None)

General Attributes

filetypeType of the file as defined with EXTENSIONS

gtgtgt fileobjectfiletypeImage

filesizeFilesize in Bytes

gtgtgt fileobjectfilesize870037L

14 Chapter 2 API

Django FileBrowser Documentation Release 357

dateDate based on timemktime

gtgtgt fileobjectdate12997603470

datetimeDatetime object

gtgtgt fileobjectdatetimedatetimedatetime(2011 3 10 13 32 27)

existsTrue if the path exists False otherwise

gtgtgt fileobjectexistsTrue

Path and URL attributes

pathPath relative to a storage location (including sitedirectory)

gtgtgt fileobjectpathuploadstestfoldertestimagejpg

path_relative_directoryPath relative to sitedirectory

gtgtgt fileobjectpath_relative_directorytestfoldertestimagejpg

path_fullAbsolute server path (based on storagepath)

gtgtgt fileobjectpath_fullabsolutepathtoserverlocationtestfoldertestimagejpg

dirnameNew in version 34

The directory (not including sitedirectory)

gtgtgt fileobjectdirnametestfolder

urlURL for the filefolder (based on storageurl)

gtgtgt fileobjecturlmediauploadstestfoldertestimagejpg

Image attributes

The image attributes are only useful if the FileObject represents an image

dimensionsImage dimensions as a tuple

21 API 15

Django FileBrowser Documentation Release 357

gtgtgt fileobjectdimensions(1000 750)

widthImage width in px

gtgtgt fileobjectwidth1000

heightImage height in px

gtgtgt fileobjectheight750

aspectratioAspect ratio (float format)

gtgtgt fileobjectaspectratio133534908

orientationImage orientation either Landscape or Portrait

gtgtgt fileobjectorientationLandscape

Folder attributes

The folder attributes make sense when the FileObject represents a directory (not a file)

directory

Deprecated since version 353 Use path_relative_directory instead

folder

Deprecated since version 353 Use dirname instead

is_folderTrue if path is a folder

gtgtgt fileobjectis_folderFalse

is_emptyTrue if the folder is empty False if the folder is not empty or the FileObject is not a folder

gtgtgt fileobjectis_emptyFalse

Version attributes

is_versiontrue if the File is a version of another File

16 Chapter 2 API

Django FileBrowser Documentation Release 357

gtgtgt fileobjectis_versionFalsegtgtgt versionis_versionTrue

versions_basedirThe relative path (from storage location) to the main versions folder Either VERSIONS_BASEDIR orsitedirectory

gtgtgt fileobjectversions_basedir_versionsgtgtgt versionversions_basedir_versions

originalReturns the original FileObject

gtgtgt fileobjectoriginalltFileObject uploadstestfoldertestimagejpggtgtgtgt versionoriginalltFileObject uploadstestfoldertestimagejpggt

original_filenameGet the filename of an original image from a version

gtgtgt fileobjectoriginal_filenametestimagejpggtgtgt versionoriginal_filenametestimagejpg

Methods

Version methods

versions()List all filenames based on VERSIONS

gtgtgt fileobjectversions()[_versionstestfoldertestimage_admin_thumbnailjpg_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionversions()[]

Note The versions are not being generated

admin_versions()List all filenames based on ADMIN_VERSIONS

gtgtgt fileobjectadmin_versions()[_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg

21 API 17

Django FileBrowser Documentation Release 357

_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionadmin_versions()[]

Note The versions are not being generated

version_name(version_suffix)Get the filename for a version

gtgtgt fileobjectversion_name(medium)testimage_mediumjpg

Note The version is not being generated

version_path(version_suffix)Get the path for a version

gtgtgt fileobjectversion_path(medium)_versionstestfoldertestimage_mediumjpg

Note The version is not being generated

version_generate(version_suffix)Generate a version

gtgtgt fileobjectversion_generate(medium)ltFileObject uploadstestfoldertestimage_mediumjpggt

Please note that a version is only generated if it does not already exist or if the original image is newer than theexisting version

Delete methods

delete()Delete the File or Folder from the server

Warning If you delete a Folder all items within the folder are being deleted

delete_versions()Delete all VERSIONS

delete_admin_versions()Delete all ADMIN_VERSIONS

18 Chapter 2 API

CHAPTER 3

Fields amp Widgets

31 Fields amp Widgets

The FileBrowseField is a custom model field which returns a FileObject The widgets FileInput and ClearableFileIn-put are used with the admin app in order to show an additional thumbnail for images

311 FileBrowseField

class FileBrowseField(max_length[ site directory extensions format options])A subclass of CharField referencing a media file within Returns a FileObject

Parameters

bull site ndash A FileBrowser site (defaults to the main site) see FileBrowser Site

bull directory ndash Directory to browse when clicking the search icon

bull extensions ndash List of allowed extensions see Extensions and Formats

bull format ndash A key from SELECT_FORMATS in order to restrict the selection to specificfiletypes see Extensions and Formats

For example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 directory=images extensions=[jpg] blank=True null=True)document = FileBrowseField(PDF max_length=200 directory=documents extensions=[pdfdoc] blank=True null=True)

FileBrowseField in Templates

You can use all attributes from FileObject

blogentryimage ltimg src= publicationimageurl gt

ifequal blogentryimageimage_orientation landscape ltimg src= blogentryimageurl class=landscape gt

endifequal

19

Django FileBrowser Documentation Release 357

Showing Thumbnail in the Changelist

To show a thumbnail with the changelist you can define a ModelAdmin method

from filebrowsersettings import ADMIN_THUMBNAIL

def image_thumbnail(self obj)if objimage and objimagefiletype == Image

return ltimg src=s gt objimageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Using the FileBrowseField with TinyMCE

In order to replace the TinyMCE imagefile manager with the FileBrowser you have to use a FileBrowser CallbackTherersquos an example TinyMCE configuration file in staticjs called TinyMCEAdminjs You can either copy theFileBrowserCallback to your own file or just use tinymce_setupjs (which comes with django-grappelli)

Just add these lines to your ModelAdmin asset definitions

class Mediajs = [pathtotinymcejscriptstiny_mcetiny_mcejs

pathtoyourtinymce_setupjs]

312 FileInput

Subclass of FileInput with an additional thumbnail

from filebrowserwidgets import FileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget FileInput

313 ClearableFileInput

Subclass of ClearableFileInput with an additional thumbnail

from filebrowserwidgets import ClearableFileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget ClearableFileInput

314 Django FileField and the FileBrowser

Return a FileObject from a FileField or ImageField with

20 Chapter 3 Fields amp Widgets

Django FileBrowser Documentation Release 357

from filebrowserbase import FileObject

image_upload = modelsImageField(uImage (Upload) max_length=250 upload_to=image_upload_path blank=True null=True)

def image(self)if selfimage_upload

return FileObject(selfimage_uploadpath)return None

In order show a thumbnail with your changelist you could use a ModelAdmin method

from filebrowserbase import FileObject

def image_thumbnail(self obj)if objimage_upload

image = FileObject(objimage_uploadpath)if imagefiletype == Image

return ltimg src=s gt imageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Note There are different ways to achieve this The above examples show one of several options

31 Fields amp Widgets 21

Django FileBrowser Documentation Release 357

22 Chapter 3 Fields amp Widgets

CHAPTER 4

Admin Interface

41 Admin Interface

The main FileBrowser admin application is an extension for the Django admin interface in order to browser yourmedia folder upload and renamedelete files

411 FileBrowser Site

New in version 340

class FileBrowserSite(name=None app_name=rsquofilebrowserrsquo storage=default_storage)Respresents the FileBrowser admin application (similar to Djangorsquos admin site)

Parameters

bull name ndash A name for the site defaults to None

bull app_name ndash Defaults to lsquofilebrowserrsquo

bull storage ndash A custom storage engine defaults to Djangos default storage

Similar to djangocontribadmin you first need to add a filebrowsersite to your admin interface Inyour urlspy import the default FileBrowser site (or your custom site) and add the site to your URL-patterns (beforeany admin-urls)

from filebrowsersites import site

urlpatterns = patterns(url(r^adminurlfilebrowser include(siteurls))

)

Now you are able to browse the location defined with the storage engine associated to your site

from djangocorefilesstorage import DefaultStoragefrom filebrowsersites import FileBrowserSite

Default FileBrowser sitesite = FileBrowserSite(name=filebrowser storage=DefaultStorage())

My Custom FileBrowser sitecustom_site = FileBrowserSite(name=custom_filebrowser storage=DefaultStorage())custom_sitedirectory = custom_uploads

23

Django FileBrowser Documentation Release 357

Note The module variable site from filebrowsersites is the default FileBrowser application

412 Custom Actions

New in version 340

Similar to Djangorsquos admin actions you can define your FileBrowser actions and thus automate the typical tasks ofyour users Registered custom actions are listed in the detail view of a file and a user can select a single action at atime The selected action will then be applied to the file

The default FileBrowser image actions such as ldquoFlip Verticalrdquo or ldquoRotate 90deg Clockwiserdquo are in fact implemented ascustom actions (see the module filebrowseractions)

Writing Your Own Actions

Custom actions are simple functions

def foo(request fileobjects) Do something with the fileobjects

The first parameter is a HttpRequest object (representing the submitted form in which a user selected the action)and the second parameter is a list of FileObjects to which the action should be applied

The list contains exactly one instance of FileObject (representing the file from the detail view) but this may change inthe future as custom actions may become available also in browse views (similar to admin actions applied to a list ofchecked objects)

Registering an Action

In order to make your action visible you need to register it with a FileBrowser site

siteadd_action(foo)

Once registered the action will appear in the detail view of a file You can also give your action a short description

fooshort_description = Do foo with the File

This short description will then appear in the list of available actions If you do not provide a short description thefunction name will be used instead and FileBrowser will replace any underscores in the function name with spaces

Associating Actions with Specific Files

Each custom action can be associated with a specific file type (eg images audio file etc) to which it applies In orderto do that you need to define a predicatefilter function which takes a single argument (FileObject) and returns Trueif your action is applicable to that FileObject Finally you need to register this filter function with your action

fooapplies_to(lambda fileobject fileobjectfiletype == Image)

In the above example foo will appear in the action list only for image files If you do not specify any filter functionfor your action FileBrowser considers the action as applicable to all files

24 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

Messages amp Intermediate Pages

You can provide a feedback to a user about a successful or failed execution of an action by using a message Forexample

from djangocontrib import messages

def desaturate_image(request fileobjects)for f in fileobjects

Desaturate the imagemessagesadd_message(request messagesSUCCESS _(Image s was desaturated) ffilename)

Some actions may require user confirmation (eg in order to prevent accidental and irreversible modification tofiles) In order to that follow the same pattern as with Djangorsquos admin action and return a HttpResponse objectfrom your action Good practice for intermediate pages is to implement a confirm view and have your action returnHttpResponseRedirect

def crop_image(request fileobjects)files = ampf=join([fpath_relative for f in fileobjects])return HttpResponseRedirect(confirmaction=crop_imageampf=s files)

413 File Storages

New in version 340

You have the option to specify which file storage engine a FileBrowser should use to browseuploadmodify yourmedia files This enables you to use a FileBrowser even if your media files are located at some remote system Seealso the Djangorsquos documentation on storages httpsdocsdjangoprojectcomendevtopicsfiles

To associate a FileBrowser site with a particular storage engine set the storage property of a site object

from djangocorefilesstorage import FileSystemStoragesitestorage = FileSystemStorage(location=pathtomediadirectory base_url=media)

For storage classes other than FileSystemStorage (or those that inherit from that class) therersquos more effort involved inproviding a storage object that can be used with FileBrowser See StorageMixin Class

Note Prior FileBrowser 34 the way to specify FileBrowserlsquos MEDIA_ROOT and MEDIA_URL was via settingspyStarting from version 34 those variables are associated with the storage instance and you can set them as illustratedin the above example

Warning For the reason of backward compatibility FileBrowser settings FILEBROWSER_MEDIA_ROOT andFILEBROWSER_MEDIA_URL can still be used to customize FileBrowser as long as yoursquore using the defaultFileBrowserlsquos site without having changed its storage engine In the next major release of FileBrowser thesesettings will be removed

StorageMixin Class

A FileBrowser uses the Djangorsquos Storage class to access media files However the API of the Storageclass does not provide all methods necessary for FileBrowserrsquos functionality A StorageMixin class fromfilebrowserstorage module therefore defines all the additional methods that a FileBrowser requires

isdir(self name)Returns true if name exists and is a directory

41 Admin Interface 25

Django FileBrowser Documentation Release 357

isfile(self name)Returns true if name exists and is a regular file

move(self old_file_name new_file_name allow_overwrite=False)Moves safely a file from one location to another If allow_ovewrite==False and new_file_nameexists raises an exception

makedirs(self name)Creates all missing directories specified by name Analogue to osmkdirs()

414 Views

All views use the staff_member_requird and path_exists decorator in order to check if the server pathactually exists Some views also use the file_exists decorator

bull Browse fb_browse Browse a directory on your server Returns a FileListing

ndash Optional query string args dir o ot q p filter_date filter_type type

bull Create directory fb_createdir Create a new folder on your server

ndash Optional query string args dir

ndash Signals filebrowser_pre_createdir filebrowser_post_createdir

bull Upload fb_upload Multiple upload

ndash Optional query string args dir type

ndash Signals filebrowser_pre_upload filebrowser_post_upload

bull Edit fb_edit Edit a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_rename filebrowser_post_rename

You are able to apply custom actions (see Custom Actions) to the edit-view

bull Confirm delete fb_confirm_delete Confirm the deletion of a file or folder

ndash Required query string args filename

ndash Optional query string args dir

If you try to delete a folder all filesfolders within this folder are listed on this page

bull Delete fb_delete Delete a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_delete filebrowser_post_delete

Warning If you delete a Folder all items within this Folder are being deleted

bull Version fb_version Generate a version of an image as defined with ADMIN_VERSIONS

ndash Required query string args filename

ndash Optional Query string args dir

This is a helper used by the FileBrowseField and TinyMCE for selecting a version

26 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

415 Signals

The FileBrowser sends a couple of different signals Please take a look at the module filebrowsersignals for furtherexplanation on the provided arguments

bull filebrowser_pre_upload Sent before a an Upload starts

bull filebrowser_post_upload Sent after an Upload has finished

bull filebrowser_pre_delete Sent before an Item (File Folder) is deleted

bull filebrowser_post_delete Sent after an Item (File Folder) has been deleted

bull filebrowser_pre_createdir Sent before a new Folder is created

bull filebrowser_post_createdir Sent after a new Folder has been created

bull filebrowser_pre_rename Sent before an Item (File Folder) is renamed

bull filebrowser_post_rename Sent after an Item (File Folder) has been renamed

bull filebrowser_actions_pre_apply Sent before a custom action is applied

bull filebrowser_actions_post_apply Sent after a custom action has been applied

Example for using these Signals

Herersquos a small example for using the above Signals

from filebrowser import signals

def pre_upload_callback(sender kwargs)Receiver function called before an upload startsprint Pre Upload Callbackprint kwargs kwargs

signalsfilebrowser_pre_uploadconnect(pre_upload_callback)

def post_upload_callback(sender kwargs)Receiver function called each time an upload has finishedprint Post Upload Callbackprint kwargs kwargs You can use all attributes available with the FileObject This is just an example print Filesize kwargs[file]filesizeprint Orientation kwargs[file]orientationprint Extension kwargs[file]extension

signalsfilebrowser_post_uploadconnect(post_upload_callback)

41 Admin Interface 27

Django FileBrowser Documentation Release 357

28 Chapter 4 Admin Interface

CHAPTER 5

Image Versions

51 Versions

With the FileBrowser you are able to define different versionssizes for images This enables you to save an originalimage on your server while having different versions of that image to automatically fit your websites grid Versionsare also useful for responsiveadaptive layouts

511 Defining Versions

New in version 340 methods

First you need to know which versionssizes of an image yoursquod like to generate with your website Letrsquos say yoursquoreusing a 12 column grid with 60px for each column and 20px margin (which is a total of 940px) With this grid youcould (for example) define these image versions

FILEBROWSER_VERSIONS_BASEDIR = _versionsFILEBROWSER_VERSIONS =

admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

Use the methods argument if you need to add a filter

def grayscale(im)Convert image to grayscaleif immode = L

im = imconvert(L)return im

FILEBROWSER_VERSIONS = big verbose_name Big (6 col) width 460 height opts methods [grayscale]

)

29

Django FileBrowser Documentation Release 357

512 Versions and the Admin

When using the FileBrowser with the admin interface you need to define ADMIN_VERSIONS andADMIN_THUMBNAIL (see Settings) ADMIN_VERSIONS are available with the admin ie you are able to seethese versions with the image detail view and you are able to select the versions with the FileBrowseField model field

FILEBROWSER_ADMIN_VERSIONS = [thumbnail small medium big large]FILEBROWSER_ADMIN_THUMBNAIL = admin_thumbnail

513 Versions and the Frontend

With your templates you have two different tags to choose from version and version_object With bothtags the version will be generated if it doesnrsquot already exist OR if the original image is newer than the version Inorder to update an image you just overwrite the original image and the versions will be generated automatically (asyou request them within your template)

A Model example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 blank=True null=True)

With your templates use version if you simply need to retrieve the URL or version_object if you need to geta FileObject

lt-- load filebrowser templatetags --gt load fb_versions

lt-- get the url with version --gtltimg src= version blogentryimage medium gt

lt-- get a fileobject with version_object --gt version_object blogentryimage medium as version_medium version_mediumwidth ltimg src= version_medium gt

Templatetag version

RetrievesGenerates a version and returns an URL

version modelfield_name version_prefix

Templatetag version_object

RetrievesGenerates a version and returns a FileObject

version_object modelfield_name version_prefix as variable

Note With both templatetags version_prefix can either be a string or a variable If version_prefix is astring use quotes

30 Chapter 5 Image Versions

Django FileBrowser Documentation Release 357

514 Versions in Views

If you have a FileObject you can generateretrieve a version with

v = objimageversion_generate(version_prefix) returns a FileObject

515 Placeholder

When developing on a locale machine or a development-server you might not have all the images (resp media-files)available that are on your production instance and downloading these files on a regular basis might not be an option

In that case you can use a placeholder instead of a version You just need to define the PLACEHOLDER and overwritethe settings SHOW_PLACEHOLDER andor FORCE_PLACEHOLDER (see Placeholder)

516 Management Commands

fb_version_generateIf you need to generate certain (or all) versions type

python managepy fb_version_generate

fb_version_removeIf you need to generate certain (or all) versions type

python managepy fb_version_generate

Warning Please be very careful with this command

51 Versions 31

Django FileBrowser Documentation Release 357

32 Chapter 5 Image Versions

CHAPTER 6

Help

61 Help

611 FAQ

Why should I use the FileBrowser

If you need your editors or customers to manage files the FileBrowser is an alternative to an FTP-client Moreoveryou are able to define different image versions according to your websites grid Alternatives to the FileBrowser can befound at httpdjangopackagescomgridsgfile-managers

Do I need Grappelli

Grappelli is a requirement for using the FileBrowser There are several filebrowser-no-grappelli repositories (most ofthem on GitHub) but we donrsquot follow the development

I need help

see Troubleshooting

Why are there no fancy effects

The FileBrowser is about managing files We think that you should prepare your files before uploading them to theserver

How do I upload to another server

Use a custom storage engine see httpsdocsdjangoprojectcomen16howtocustom-file-storage

Why do I need image-versions

You need image-versions if your website is based on a grid

33

Django FileBrowser Documentation Release 357

Is the FileBrowser stable

Wersquove developed the FileBrowser for a couple of years and use it with almost all of our clients That said Grappelli isthe more stable and mature application

How can I contribute

Help is very much needed and appreciated Test the FileBrowser and submit feedbackpatches

Who develops the FileBrowser

The FileBrowser is developed and maintained by Patrick Kranzlmuumlller amp Axel Swoboda of vonautomatisch

612 Troubleshooting

Check your setup

Please check if the problem is caused by your setup

bull Read Quick start guide

bull Check if the staticmedia-files are served correctly

bull Make sure you have removed all custom FileBrowser templates from all locations in TEMPLATE_DIRS orcheck that these templates are compatible with the FileBrowser

Run the tests

Start the shell and type

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Check issues

If your setup is fine please check if your problem is a known issue

bull Take a look at all FileBrowser Issues (incuding closed) and search the FileBrowser Google-Group

Add a ticket

If you think yoursquove found a bug please add a ticket

bull Try to describe your problem as precisely as possible

bull Tell us what you did in order to solve the problem

bull Tell us what version of the FileBrowser you are using

bull Tell us what version of Django you are using

34 Chapter 6 Help

Django FileBrowser Documentation Release 357

bull Please do NOT add tickets if yoursquore having problems with serving staticmedia-files (because this is not relatedto the FileBrowser)

bull Please do NOT add tickets referring to Djangos trunk version

bull At best add a patch

Note Be aware that we may close issues not following these guidlines without further notifications

613 Translation

Translation is done via Transifex

Supported Languages

see httpswwwtransifexnetprojectspdjango-filebrowserresourcedjangopo

614 FileBrowser 35 Release Notes

FileBrowser 35 is compatible with Django 14151617 as well as Grappelli 242526

Update from FileBrowser 34x

bull Update Django to 14151617 and check httpsdocsdjangoprojectcomendevreleases14 orhttpsdocsdjangoprojectcomendevreleases15 or httpsdocsdjangoprojectcomendevreleases16

bull Update Grappelli to 24x25x26x

bull Update FileBrowser to 35x

62 Changelog

621 358 (not yet released)

622 357 (September 10th 2014)

bull New Compatibility with Django 17 and Grappelli 26x

bull Improved Updated tests because of the new random suffix with get_available_name (django storage)

bull Improved Added an icon in order to mark finished uploads

bull Improved Show resulting filename (eg with suffix converted) after successful upload

bull Fixed Permissions with file upload

bull Fixed Unified json response with _upload_file (no matter if file already exists or not)

623 356 (April 16th 2014)

bull Fixed Displaying pagination correctly with lots of entries

62 Changelog 35

Django FileBrowser Documentation Release 357

624 355 (April 13th 2014)

bull New Added client-side (JavaScript) file extension validation to the AJAX uploader

bull New Added experimental Python 33 support

bull Improved Tests with convertnormalize (removed special chars from test filename)

bull Fixed File selection after using search box (CKEditor)

bull Fixed Removed encoding of file URIs with CKEditor

625 354 (February 21st 2014)

bull Fixed Placeholder functionality (including tests)

bull Fixed Convertnormalize filenames (including tests)

bull Fixed Handling uppercase extensions with browse

626 353 (January 7 2014)

bull New added path_full to FileObject

bull Improved added docx to EXTENSIONS

bull Improved Recommend pillow instead of PIL as a requirement

bull Improved Added additional test cases

bull Improved Updated documentation

bull Improved Consistent use of storage (eg storagelocation storageurl)

bull Improved Removed unnecessary functions (eg url_join url_strip)

bull Improved Moved sort_by_attr to FileListing

bull Improved Regex matches with file versions on browse

bull Improved Using djangoconfurls (with djangoconfurlsdefaults as fallback)

bull Improved Adding CONTRIBUTINGrst

bull Improved Removed static Media inner class with fields

bull Improved Removed search icon with fields (has not being used)

bull Improved Added custom class attributes with filebrowser field

bull Improved Updated translations

bull Fixed fixed exception handling with python 25

bull Fixed fixes dir with SEARCH_TRAVERSE true and version select

bull Fixed Make Django FileUploadHandlers work (also fixed a memory leak)

bull Fixed return correct filename with OVERWRITE_EXISTING

bull Fixed fb_version_generate with FILEBROWSER_VERSIONS_BASEDIR

bull Fixed Table sorting with ascdesc

bull Fixed Added DeprecationWarning for FileObjectdirectory and FileObjectfolder

36 Chapter 6 Help

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

Django FileBrowser Documentation Release 357

10 Chapter 1 Installation and Setup

CHAPTER 2

API

21 API

211 FileListing

class FileListing(path filter_func=None sorting_by=None sorting_order=None)Returns a list of FileObjects for a server path see FileObject

Parameters

bull path ndash Relative path to a location within sitestoragelocation

bull filter_func ndash Filter function see example below

bull sorting_by ndash Sort the files by any attribute of FileObject

bull sorting_order ndash Sorting order either ldquoascrdquo or ldquodescrdquo

If you want to list all files within a storage location you do

from filebrowsersites import sitefrom filebrowserbase import FileListingfilelisting = FileListing(sitestoragelocation sorting_by=date sorting_order=desc)

Use a custom filter function to limit the list of files

def filter_filelisting(item) item is a FileObjectreturn itemfiletype = Folder

filelisting = FileListing(sitestoragelocation filter_func=filter_listing sorting_by=date sorting_order=desc)

Methods

For the below examples wersquore using this folder-structure

mediauploadstestfoldertestimagejpgmediauploadsblog1imagesblogimagejpg

Note We defined filter_browse as filter_func (see sitespy) And we did not define aVERSIONS_BASEDIR for this demonstration though it is highly recommended to use one

11

Django FileBrowser Documentation Release 357

listing()Returns all items for the given path with oslistdir(path)

gtgtgt for item in filelistinglisting() print itemblogtestfolder

walk()Returns all items for the given path with oswalk(path)

gtgtgt for item in filelistingwalk() print itemblogblog1blog1imagesblog1imagesblogimagejpgblog1imagesblogimage_admin_thumbnailjpgblog1imagesblogimage_mediumjpgblog1imagesblogimage_smalljpgblog1imagesblogimage_thumbnailjpgtestfoldertestfoldertestimagejpg

files_listing_total()Returns a sorted list of FileObjects for listing()

gtgtgt for item in filelistingfiles_listing_total() print itemuploadsbloguploadstestfolder

files_walk_total()Returns a sorted list of FileObjects for walk()

gtgtgt for item in filelistingfiles_walk_total() print itemuploadsbloguploadsblog1uploadsblog1imagesuploadsblog1imagesblogimagejpguploadsblog1imagesblogimage_admin_thumbnailjpguploadsblog1imagesblogimage_mediumjpguploadsblog1imagesblogimage_smalljpguploadsblog1imagesblogimage_thumbnailjpguploadstestfolderuploadstestfoldertestimagejpg

files_listing_filtered()Returns a sorted and filtered list of FileObjects for listing()

gtgtgt for item in filelistingfiles_listing_filtered() print itemuploadsbloguploadstestfolder

files_walk_filtered()Returns a sorted and filtered list of FileObjects for walk()

12 Chapter 2 API

Django FileBrowser Documentation Release 357

gtgtgt for item in filelistingfiles_walk_filtered() print itemuploadsbloguploadsblog1uploadsblog1imagesuploadsblog1imagesblogimagejpguploadstestfolderuploadstestfoldertestimagejpg

Note The versions are not listed (compared with files_walk_total) because of filter_func

results_listing_total()Number of total files based on files_listing_total()

gtgtgt filelistingresults_listing_total()2

results_walk_total()Number of total files based on files_walk_total()

gtgtgt filelistingresults_walk_total()10

results_listing_filtered()Number of filtered files based on files_listing_filtered()

gtgtgt filelistingresults_listing_filtered()2

results_walk_filtered()Number of filtered files based on files_walk_filtered()

gtgtgt filelistingresults_walk_filtered()6

212 FileObject

class FileObject(path site=None)An object representing a media file

Parameters

bull path ndash Relative path to a location within sitestoragelocation

bull site ndash An optional FileBrowser Site

For example

from filebrowsersites import sitefrom filebrowserbase import FileObjectfileobject = FileObject(ospathjoin(sitedirectorytestfoldertestimagejpg))version = FileObject(ospathjoin(fileobjectversions_basedir testfolder testimage_mediumjpg))

21 API 13

Django FileBrowser Documentation Release 357

Attributes

Initial Attributes

pathPath relative to a storage location (including sitedirectory)

gtgtgt fileobjectpathuploadstestfoldertestimagejpg

headThe directory name of pathname path

gtgtgt fileobjectheaduploadstestfolder

filenameName of the file (including the extension) or name of the folder

gtgtgt fileobjectfilenametestimagejpg

filename_lowerLower type of filename

filename_rootFilename without extension

gtgtgt fileobjectfilename_roottestimage

extensionFile extension including the dot With a folder the extensions is None

gtgtgt fileobjectextensionjpg

mimetypeMimetype based on httpdocspythonorglibrarymimetypeshtml

gtgtgt fileobjectmimetype(imagejpeg None)

General Attributes

filetypeType of the file as defined with EXTENSIONS

gtgtgt fileobjectfiletypeImage

filesizeFilesize in Bytes

gtgtgt fileobjectfilesize870037L

14 Chapter 2 API

Django FileBrowser Documentation Release 357

dateDate based on timemktime

gtgtgt fileobjectdate12997603470

datetimeDatetime object

gtgtgt fileobjectdatetimedatetimedatetime(2011 3 10 13 32 27)

existsTrue if the path exists False otherwise

gtgtgt fileobjectexistsTrue

Path and URL attributes

pathPath relative to a storage location (including sitedirectory)

gtgtgt fileobjectpathuploadstestfoldertestimagejpg

path_relative_directoryPath relative to sitedirectory

gtgtgt fileobjectpath_relative_directorytestfoldertestimagejpg

path_fullAbsolute server path (based on storagepath)

gtgtgt fileobjectpath_fullabsolutepathtoserverlocationtestfoldertestimagejpg

dirnameNew in version 34

The directory (not including sitedirectory)

gtgtgt fileobjectdirnametestfolder

urlURL for the filefolder (based on storageurl)

gtgtgt fileobjecturlmediauploadstestfoldertestimagejpg

Image attributes

The image attributes are only useful if the FileObject represents an image

dimensionsImage dimensions as a tuple

21 API 15

Django FileBrowser Documentation Release 357

gtgtgt fileobjectdimensions(1000 750)

widthImage width in px

gtgtgt fileobjectwidth1000

heightImage height in px

gtgtgt fileobjectheight750

aspectratioAspect ratio (float format)

gtgtgt fileobjectaspectratio133534908

orientationImage orientation either Landscape or Portrait

gtgtgt fileobjectorientationLandscape

Folder attributes

The folder attributes make sense when the FileObject represents a directory (not a file)

directory

Deprecated since version 353 Use path_relative_directory instead

folder

Deprecated since version 353 Use dirname instead

is_folderTrue if path is a folder

gtgtgt fileobjectis_folderFalse

is_emptyTrue if the folder is empty False if the folder is not empty or the FileObject is not a folder

gtgtgt fileobjectis_emptyFalse

Version attributes

is_versiontrue if the File is a version of another File

16 Chapter 2 API

Django FileBrowser Documentation Release 357

gtgtgt fileobjectis_versionFalsegtgtgt versionis_versionTrue

versions_basedirThe relative path (from storage location) to the main versions folder Either VERSIONS_BASEDIR orsitedirectory

gtgtgt fileobjectversions_basedir_versionsgtgtgt versionversions_basedir_versions

originalReturns the original FileObject

gtgtgt fileobjectoriginalltFileObject uploadstestfoldertestimagejpggtgtgtgt versionoriginalltFileObject uploadstestfoldertestimagejpggt

original_filenameGet the filename of an original image from a version

gtgtgt fileobjectoriginal_filenametestimagejpggtgtgt versionoriginal_filenametestimagejpg

Methods

Version methods

versions()List all filenames based on VERSIONS

gtgtgt fileobjectversions()[_versionstestfoldertestimage_admin_thumbnailjpg_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionversions()[]

Note The versions are not being generated

admin_versions()List all filenames based on ADMIN_VERSIONS

gtgtgt fileobjectadmin_versions()[_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg

21 API 17

Django FileBrowser Documentation Release 357

_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionadmin_versions()[]

Note The versions are not being generated

version_name(version_suffix)Get the filename for a version

gtgtgt fileobjectversion_name(medium)testimage_mediumjpg

Note The version is not being generated

version_path(version_suffix)Get the path for a version

gtgtgt fileobjectversion_path(medium)_versionstestfoldertestimage_mediumjpg

Note The version is not being generated

version_generate(version_suffix)Generate a version

gtgtgt fileobjectversion_generate(medium)ltFileObject uploadstestfoldertestimage_mediumjpggt

Please note that a version is only generated if it does not already exist or if the original image is newer than theexisting version

Delete methods

delete()Delete the File or Folder from the server

Warning If you delete a Folder all items within the folder are being deleted

delete_versions()Delete all VERSIONS

delete_admin_versions()Delete all ADMIN_VERSIONS

18 Chapter 2 API

CHAPTER 3

Fields amp Widgets

31 Fields amp Widgets

The FileBrowseField is a custom model field which returns a FileObject The widgets FileInput and ClearableFileIn-put are used with the admin app in order to show an additional thumbnail for images

311 FileBrowseField

class FileBrowseField(max_length[ site directory extensions format options])A subclass of CharField referencing a media file within Returns a FileObject

Parameters

bull site ndash A FileBrowser site (defaults to the main site) see FileBrowser Site

bull directory ndash Directory to browse when clicking the search icon

bull extensions ndash List of allowed extensions see Extensions and Formats

bull format ndash A key from SELECT_FORMATS in order to restrict the selection to specificfiletypes see Extensions and Formats

For example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 directory=images extensions=[jpg] blank=True null=True)document = FileBrowseField(PDF max_length=200 directory=documents extensions=[pdfdoc] blank=True null=True)

FileBrowseField in Templates

You can use all attributes from FileObject

blogentryimage ltimg src= publicationimageurl gt

ifequal blogentryimageimage_orientation landscape ltimg src= blogentryimageurl class=landscape gt

endifequal

19

Django FileBrowser Documentation Release 357

Showing Thumbnail in the Changelist

To show a thumbnail with the changelist you can define a ModelAdmin method

from filebrowsersettings import ADMIN_THUMBNAIL

def image_thumbnail(self obj)if objimage and objimagefiletype == Image

return ltimg src=s gt objimageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Using the FileBrowseField with TinyMCE

In order to replace the TinyMCE imagefile manager with the FileBrowser you have to use a FileBrowser CallbackTherersquos an example TinyMCE configuration file in staticjs called TinyMCEAdminjs You can either copy theFileBrowserCallback to your own file or just use tinymce_setupjs (which comes with django-grappelli)

Just add these lines to your ModelAdmin asset definitions

class Mediajs = [pathtotinymcejscriptstiny_mcetiny_mcejs

pathtoyourtinymce_setupjs]

312 FileInput

Subclass of FileInput with an additional thumbnail

from filebrowserwidgets import FileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget FileInput

313 ClearableFileInput

Subclass of ClearableFileInput with an additional thumbnail

from filebrowserwidgets import ClearableFileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget ClearableFileInput

314 Django FileField and the FileBrowser

Return a FileObject from a FileField or ImageField with

20 Chapter 3 Fields amp Widgets

Django FileBrowser Documentation Release 357

from filebrowserbase import FileObject

image_upload = modelsImageField(uImage (Upload) max_length=250 upload_to=image_upload_path blank=True null=True)

def image(self)if selfimage_upload

return FileObject(selfimage_uploadpath)return None

In order show a thumbnail with your changelist you could use a ModelAdmin method

from filebrowserbase import FileObject

def image_thumbnail(self obj)if objimage_upload

image = FileObject(objimage_uploadpath)if imagefiletype == Image

return ltimg src=s gt imageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Note There are different ways to achieve this The above examples show one of several options

31 Fields amp Widgets 21

Django FileBrowser Documentation Release 357

22 Chapter 3 Fields amp Widgets

CHAPTER 4

Admin Interface

41 Admin Interface

The main FileBrowser admin application is an extension for the Django admin interface in order to browser yourmedia folder upload and renamedelete files

411 FileBrowser Site

New in version 340

class FileBrowserSite(name=None app_name=rsquofilebrowserrsquo storage=default_storage)Respresents the FileBrowser admin application (similar to Djangorsquos admin site)

Parameters

bull name ndash A name for the site defaults to None

bull app_name ndash Defaults to lsquofilebrowserrsquo

bull storage ndash A custom storage engine defaults to Djangos default storage

Similar to djangocontribadmin you first need to add a filebrowsersite to your admin interface Inyour urlspy import the default FileBrowser site (or your custom site) and add the site to your URL-patterns (beforeany admin-urls)

from filebrowsersites import site

urlpatterns = patterns(url(r^adminurlfilebrowser include(siteurls))

)

Now you are able to browse the location defined with the storage engine associated to your site

from djangocorefilesstorage import DefaultStoragefrom filebrowsersites import FileBrowserSite

Default FileBrowser sitesite = FileBrowserSite(name=filebrowser storage=DefaultStorage())

My Custom FileBrowser sitecustom_site = FileBrowserSite(name=custom_filebrowser storage=DefaultStorage())custom_sitedirectory = custom_uploads

23

Django FileBrowser Documentation Release 357

Note The module variable site from filebrowsersites is the default FileBrowser application

412 Custom Actions

New in version 340

Similar to Djangorsquos admin actions you can define your FileBrowser actions and thus automate the typical tasks ofyour users Registered custom actions are listed in the detail view of a file and a user can select a single action at atime The selected action will then be applied to the file

The default FileBrowser image actions such as ldquoFlip Verticalrdquo or ldquoRotate 90deg Clockwiserdquo are in fact implemented ascustom actions (see the module filebrowseractions)

Writing Your Own Actions

Custom actions are simple functions

def foo(request fileobjects) Do something with the fileobjects

The first parameter is a HttpRequest object (representing the submitted form in which a user selected the action)and the second parameter is a list of FileObjects to which the action should be applied

The list contains exactly one instance of FileObject (representing the file from the detail view) but this may change inthe future as custom actions may become available also in browse views (similar to admin actions applied to a list ofchecked objects)

Registering an Action

In order to make your action visible you need to register it with a FileBrowser site

siteadd_action(foo)

Once registered the action will appear in the detail view of a file You can also give your action a short description

fooshort_description = Do foo with the File

This short description will then appear in the list of available actions If you do not provide a short description thefunction name will be used instead and FileBrowser will replace any underscores in the function name with spaces

Associating Actions with Specific Files

Each custom action can be associated with a specific file type (eg images audio file etc) to which it applies In orderto do that you need to define a predicatefilter function which takes a single argument (FileObject) and returns Trueif your action is applicable to that FileObject Finally you need to register this filter function with your action

fooapplies_to(lambda fileobject fileobjectfiletype == Image)

In the above example foo will appear in the action list only for image files If you do not specify any filter functionfor your action FileBrowser considers the action as applicable to all files

24 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

Messages amp Intermediate Pages

You can provide a feedback to a user about a successful or failed execution of an action by using a message Forexample

from djangocontrib import messages

def desaturate_image(request fileobjects)for f in fileobjects

Desaturate the imagemessagesadd_message(request messagesSUCCESS _(Image s was desaturated) ffilename)

Some actions may require user confirmation (eg in order to prevent accidental and irreversible modification tofiles) In order to that follow the same pattern as with Djangorsquos admin action and return a HttpResponse objectfrom your action Good practice for intermediate pages is to implement a confirm view and have your action returnHttpResponseRedirect

def crop_image(request fileobjects)files = ampf=join([fpath_relative for f in fileobjects])return HttpResponseRedirect(confirmaction=crop_imageampf=s files)

413 File Storages

New in version 340

You have the option to specify which file storage engine a FileBrowser should use to browseuploadmodify yourmedia files This enables you to use a FileBrowser even if your media files are located at some remote system Seealso the Djangorsquos documentation on storages httpsdocsdjangoprojectcomendevtopicsfiles

To associate a FileBrowser site with a particular storage engine set the storage property of a site object

from djangocorefilesstorage import FileSystemStoragesitestorage = FileSystemStorage(location=pathtomediadirectory base_url=media)

For storage classes other than FileSystemStorage (or those that inherit from that class) therersquos more effort involved inproviding a storage object that can be used with FileBrowser See StorageMixin Class

Note Prior FileBrowser 34 the way to specify FileBrowserlsquos MEDIA_ROOT and MEDIA_URL was via settingspyStarting from version 34 those variables are associated with the storage instance and you can set them as illustratedin the above example

Warning For the reason of backward compatibility FileBrowser settings FILEBROWSER_MEDIA_ROOT andFILEBROWSER_MEDIA_URL can still be used to customize FileBrowser as long as yoursquore using the defaultFileBrowserlsquos site without having changed its storage engine In the next major release of FileBrowser thesesettings will be removed

StorageMixin Class

A FileBrowser uses the Djangorsquos Storage class to access media files However the API of the Storageclass does not provide all methods necessary for FileBrowserrsquos functionality A StorageMixin class fromfilebrowserstorage module therefore defines all the additional methods that a FileBrowser requires

isdir(self name)Returns true if name exists and is a directory

41 Admin Interface 25

Django FileBrowser Documentation Release 357

isfile(self name)Returns true if name exists and is a regular file

move(self old_file_name new_file_name allow_overwrite=False)Moves safely a file from one location to another If allow_ovewrite==False and new_file_nameexists raises an exception

makedirs(self name)Creates all missing directories specified by name Analogue to osmkdirs()

414 Views

All views use the staff_member_requird and path_exists decorator in order to check if the server pathactually exists Some views also use the file_exists decorator

bull Browse fb_browse Browse a directory on your server Returns a FileListing

ndash Optional query string args dir o ot q p filter_date filter_type type

bull Create directory fb_createdir Create a new folder on your server

ndash Optional query string args dir

ndash Signals filebrowser_pre_createdir filebrowser_post_createdir

bull Upload fb_upload Multiple upload

ndash Optional query string args dir type

ndash Signals filebrowser_pre_upload filebrowser_post_upload

bull Edit fb_edit Edit a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_rename filebrowser_post_rename

You are able to apply custom actions (see Custom Actions) to the edit-view

bull Confirm delete fb_confirm_delete Confirm the deletion of a file or folder

ndash Required query string args filename

ndash Optional query string args dir

If you try to delete a folder all filesfolders within this folder are listed on this page

bull Delete fb_delete Delete a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_delete filebrowser_post_delete

Warning If you delete a Folder all items within this Folder are being deleted

bull Version fb_version Generate a version of an image as defined with ADMIN_VERSIONS

ndash Required query string args filename

ndash Optional Query string args dir

This is a helper used by the FileBrowseField and TinyMCE for selecting a version

26 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

415 Signals

The FileBrowser sends a couple of different signals Please take a look at the module filebrowsersignals for furtherexplanation on the provided arguments

bull filebrowser_pre_upload Sent before a an Upload starts

bull filebrowser_post_upload Sent after an Upload has finished

bull filebrowser_pre_delete Sent before an Item (File Folder) is deleted

bull filebrowser_post_delete Sent after an Item (File Folder) has been deleted

bull filebrowser_pre_createdir Sent before a new Folder is created

bull filebrowser_post_createdir Sent after a new Folder has been created

bull filebrowser_pre_rename Sent before an Item (File Folder) is renamed

bull filebrowser_post_rename Sent after an Item (File Folder) has been renamed

bull filebrowser_actions_pre_apply Sent before a custom action is applied

bull filebrowser_actions_post_apply Sent after a custom action has been applied

Example for using these Signals

Herersquos a small example for using the above Signals

from filebrowser import signals

def pre_upload_callback(sender kwargs)Receiver function called before an upload startsprint Pre Upload Callbackprint kwargs kwargs

signalsfilebrowser_pre_uploadconnect(pre_upload_callback)

def post_upload_callback(sender kwargs)Receiver function called each time an upload has finishedprint Post Upload Callbackprint kwargs kwargs You can use all attributes available with the FileObject This is just an example print Filesize kwargs[file]filesizeprint Orientation kwargs[file]orientationprint Extension kwargs[file]extension

signalsfilebrowser_post_uploadconnect(post_upload_callback)

41 Admin Interface 27

Django FileBrowser Documentation Release 357

28 Chapter 4 Admin Interface

CHAPTER 5

Image Versions

51 Versions

With the FileBrowser you are able to define different versionssizes for images This enables you to save an originalimage on your server while having different versions of that image to automatically fit your websites grid Versionsare also useful for responsiveadaptive layouts

511 Defining Versions

New in version 340 methods

First you need to know which versionssizes of an image yoursquod like to generate with your website Letrsquos say yoursquoreusing a 12 column grid with 60px for each column and 20px margin (which is a total of 940px) With this grid youcould (for example) define these image versions

FILEBROWSER_VERSIONS_BASEDIR = _versionsFILEBROWSER_VERSIONS =

admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

Use the methods argument if you need to add a filter

def grayscale(im)Convert image to grayscaleif immode = L

im = imconvert(L)return im

FILEBROWSER_VERSIONS = big verbose_name Big (6 col) width 460 height opts methods [grayscale]

)

29

Django FileBrowser Documentation Release 357

512 Versions and the Admin

When using the FileBrowser with the admin interface you need to define ADMIN_VERSIONS andADMIN_THUMBNAIL (see Settings) ADMIN_VERSIONS are available with the admin ie you are able to seethese versions with the image detail view and you are able to select the versions with the FileBrowseField model field

FILEBROWSER_ADMIN_VERSIONS = [thumbnail small medium big large]FILEBROWSER_ADMIN_THUMBNAIL = admin_thumbnail

513 Versions and the Frontend

With your templates you have two different tags to choose from version and version_object With bothtags the version will be generated if it doesnrsquot already exist OR if the original image is newer than the version Inorder to update an image you just overwrite the original image and the versions will be generated automatically (asyou request them within your template)

A Model example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 blank=True null=True)

With your templates use version if you simply need to retrieve the URL or version_object if you need to geta FileObject

lt-- load filebrowser templatetags --gt load fb_versions

lt-- get the url with version --gtltimg src= version blogentryimage medium gt

lt-- get a fileobject with version_object --gt version_object blogentryimage medium as version_medium version_mediumwidth ltimg src= version_medium gt

Templatetag version

RetrievesGenerates a version and returns an URL

version modelfield_name version_prefix

Templatetag version_object

RetrievesGenerates a version and returns a FileObject

version_object modelfield_name version_prefix as variable

Note With both templatetags version_prefix can either be a string or a variable If version_prefix is astring use quotes

30 Chapter 5 Image Versions

Django FileBrowser Documentation Release 357

514 Versions in Views

If you have a FileObject you can generateretrieve a version with

v = objimageversion_generate(version_prefix) returns a FileObject

515 Placeholder

When developing on a locale machine or a development-server you might not have all the images (resp media-files)available that are on your production instance and downloading these files on a regular basis might not be an option

In that case you can use a placeholder instead of a version You just need to define the PLACEHOLDER and overwritethe settings SHOW_PLACEHOLDER andor FORCE_PLACEHOLDER (see Placeholder)

516 Management Commands

fb_version_generateIf you need to generate certain (or all) versions type

python managepy fb_version_generate

fb_version_removeIf you need to generate certain (or all) versions type

python managepy fb_version_generate

Warning Please be very careful with this command

51 Versions 31

Django FileBrowser Documentation Release 357

32 Chapter 5 Image Versions

CHAPTER 6

Help

61 Help

611 FAQ

Why should I use the FileBrowser

If you need your editors or customers to manage files the FileBrowser is an alternative to an FTP-client Moreoveryou are able to define different image versions according to your websites grid Alternatives to the FileBrowser can befound at httpdjangopackagescomgridsgfile-managers

Do I need Grappelli

Grappelli is a requirement for using the FileBrowser There are several filebrowser-no-grappelli repositories (most ofthem on GitHub) but we donrsquot follow the development

I need help

see Troubleshooting

Why are there no fancy effects

The FileBrowser is about managing files We think that you should prepare your files before uploading them to theserver

How do I upload to another server

Use a custom storage engine see httpsdocsdjangoprojectcomen16howtocustom-file-storage

Why do I need image-versions

You need image-versions if your website is based on a grid

33

Django FileBrowser Documentation Release 357

Is the FileBrowser stable

Wersquove developed the FileBrowser for a couple of years and use it with almost all of our clients That said Grappelli isthe more stable and mature application

How can I contribute

Help is very much needed and appreciated Test the FileBrowser and submit feedbackpatches

Who develops the FileBrowser

The FileBrowser is developed and maintained by Patrick Kranzlmuumlller amp Axel Swoboda of vonautomatisch

612 Troubleshooting

Check your setup

Please check if the problem is caused by your setup

bull Read Quick start guide

bull Check if the staticmedia-files are served correctly

bull Make sure you have removed all custom FileBrowser templates from all locations in TEMPLATE_DIRS orcheck that these templates are compatible with the FileBrowser

Run the tests

Start the shell and type

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Check issues

If your setup is fine please check if your problem is a known issue

bull Take a look at all FileBrowser Issues (incuding closed) and search the FileBrowser Google-Group

Add a ticket

If you think yoursquove found a bug please add a ticket

bull Try to describe your problem as precisely as possible

bull Tell us what you did in order to solve the problem

bull Tell us what version of the FileBrowser you are using

bull Tell us what version of Django you are using

34 Chapter 6 Help

Django FileBrowser Documentation Release 357

bull Please do NOT add tickets if yoursquore having problems with serving staticmedia-files (because this is not relatedto the FileBrowser)

bull Please do NOT add tickets referring to Djangos trunk version

bull At best add a patch

Note Be aware that we may close issues not following these guidlines without further notifications

613 Translation

Translation is done via Transifex

Supported Languages

see httpswwwtransifexnetprojectspdjango-filebrowserresourcedjangopo

614 FileBrowser 35 Release Notes

FileBrowser 35 is compatible with Django 14151617 as well as Grappelli 242526

Update from FileBrowser 34x

bull Update Django to 14151617 and check httpsdocsdjangoprojectcomendevreleases14 orhttpsdocsdjangoprojectcomendevreleases15 or httpsdocsdjangoprojectcomendevreleases16

bull Update Grappelli to 24x25x26x

bull Update FileBrowser to 35x

62 Changelog

621 358 (not yet released)

622 357 (September 10th 2014)

bull New Compatibility with Django 17 and Grappelli 26x

bull Improved Updated tests because of the new random suffix with get_available_name (django storage)

bull Improved Added an icon in order to mark finished uploads

bull Improved Show resulting filename (eg with suffix converted) after successful upload

bull Fixed Permissions with file upload

bull Fixed Unified json response with _upload_file (no matter if file already exists or not)

623 356 (April 16th 2014)

bull Fixed Displaying pagination correctly with lots of entries

62 Changelog 35

Django FileBrowser Documentation Release 357

624 355 (April 13th 2014)

bull New Added client-side (JavaScript) file extension validation to the AJAX uploader

bull New Added experimental Python 33 support

bull Improved Tests with convertnormalize (removed special chars from test filename)

bull Fixed File selection after using search box (CKEditor)

bull Fixed Removed encoding of file URIs with CKEditor

625 354 (February 21st 2014)

bull Fixed Placeholder functionality (including tests)

bull Fixed Convertnormalize filenames (including tests)

bull Fixed Handling uppercase extensions with browse

626 353 (January 7 2014)

bull New added path_full to FileObject

bull Improved added docx to EXTENSIONS

bull Improved Recommend pillow instead of PIL as a requirement

bull Improved Added additional test cases

bull Improved Updated documentation

bull Improved Consistent use of storage (eg storagelocation storageurl)

bull Improved Removed unnecessary functions (eg url_join url_strip)

bull Improved Moved sort_by_attr to FileListing

bull Improved Regex matches with file versions on browse

bull Improved Using djangoconfurls (with djangoconfurlsdefaults as fallback)

bull Improved Adding CONTRIBUTINGrst

bull Improved Removed static Media inner class with fields

bull Improved Removed search icon with fields (has not being used)

bull Improved Added custom class attributes with filebrowser field

bull Improved Updated translations

bull Fixed fixed exception handling with python 25

bull Fixed fixes dir with SEARCH_TRAVERSE true and version select

bull Fixed Make Django FileUploadHandlers work (also fixed a memory leak)

bull Fixed return correct filename with OVERWRITE_EXISTING

bull Fixed fb_version_generate with FILEBROWSER_VERSIONS_BASEDIR

bull Fixed Table sorting with ascdesc

bull Fixed Added DeprecationWarning for FileObjectdirectory and FileObjectfolder

36 Chapter 6 Help

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

CHAPTER 2

API

21 API

211 FileListing

class FileListing(path filter_func=None sorting_by=None sorting_order=None)Returns a list of FileObjects for a server path see FileObject

Parameters

bull path ndash Relative path to a location within sitestoragelocation

bull filter_func ndash Filter function see example below

bull sorting_by ndash Sort the files by any attribute of FileObject

bull sorting_order ndash Sorting order either ldquoascrdquo or ldquodescrdquo

If you want to list all files within a storage location you do

from filebrowsersites import sitefrom filebrowserbase import FileListingfilelisting = FileListing(sitestoragelocation sorting_by=date sorting_order=desc)

Use a custom filter function to limit the list of files

def filter_filelisting(item) item is a FileObjectreturn itemfiletype = Folder

filelisting = FileListing(sitestoragelocation filter_func=filter_listing sorting_by=date sorting_order=desc)

Methods

For the below examples wersquore using this folder-structure

mediauploadstestfoldertestimagejpgmediauploadsblog1imagesblogimagejpg

Note We defined filter_browse as filter_func (see sitespy) And we did not define aVERSIONS_BASEDIR for this demonstration though it is highly recommended to use one

11

Django FileBrowser Documentation Release 357

listing()Returns all items for the given path with oslistdir(path)

gtgtgt for item in filelistinglisting() print itemblogtestfolder

walk()Returns all items for the given path with oswalk(path)

gtgtgt for item in filelistingwalk() print itemblogblog1blog1imagesblog1imagesblogimagejpgblog1imagesblogimage_admin_thumbnailjpgblog1imagesblogimage_mediumjpgblog1imagesblogimage_smalljpgblog1imagesblogimage_thumbnailjpgtestfoldertestfoldertestimagejpg

files_listing_total()Returns a sorted list of FileObjects for listing()

gtgtgt for item in filelistingfiles_listing_total() print itemuploadsbloguploadstestfolder

files_walk_total()Returns a sorted list of FileObjects for walk()

gtgtgt for item in filelistingfiles_walk_total() print itemuploadsbloguploadsblog1uploadsblog1imagesuploadsblog1imagesblogimagejpguploadsblog1imagesblogimage_admin_thumbnailjpguploadsblog1imagesblogimage_mediumjpguploadsblog1imagesblogimage_smalljpguploadsblog1imagesblogimage_thumbnailjpguploadstestfolderuploadstestfoldertestimagejpg

files_listing_filtered()Returns a sorted and filtered list of FileObjects for listing()

gtgtgt for item in filelistingfiles_listing_filtered() print itemuploadsbloguploadstestfolder

files_walk_filtered()Returns a sorted and filtered list of FileObjects for walk()

12 Chapter 2 API

Django FileBrowser Documentation Release 357

gtgtgt for item in filelistingfiles_walk_filtered() print itemuploadsbloguploadsblog1uploadsblog1imagesuploadsblog1imagesblogimagejpguploadstestfolderuploadstestfoldertestimagejpg

Note The versions are not listed (compared with files_walk_total) because of filter_func

results_listing_total()Number of total files based on files_listing_total()

gtgtgt filelistingresults_listing_total()2

results_walk_total()Number of total files based on files_walk_total()

gtgtgt filelistingresults_walk_total()10

results_listing_filtered()Number of filtered files based on files_listing_filtered()

gtgtgt filelistingresults_listing_filtered()2

results_walk_filtered()Number of filtered files based on files_walk_filtered()

gtgtgt filelistingresults_walk_filtered()6

212 FileObject

class FileObject(path site=None)An object representing a media file

Parameters

bull path ndash Relative path to a location within sitestoragelocation

bull site ndash An optional FileBrowser Site

For example

from filebrowsersites import sitefrom filebrowserbase import FileObjectfileobject = FileObject(ospathjoin(sitedirectorytestfoldertestimagejpg))version = FileObject(ospathjoin(fileobjectversions_basedir testfolder testimage_mediumjpg))

21 API 13

Django FileBrowser Documentation Release 357

Attributes

Initial Attributes

pathPath relative to a storage location (including sitedirectory)

gtgtgt fileobjectpathuploadstestfoldertestimagejpg

headThe directory name of pathname path

gtgtgt fileobjectheaduploadstestfolder

filenameName of the file (including the extension) or name of the folder

gtgtgt fileobjectfilenametestimagejpg

filename_lowerLower type of filename

filename_rootFilename without extension

gtgtgt fileobjectfilename_roottestimage

extensionFile extension including the dot With a folder the extensions is None

gtgtgt fileobjectextensionjpg

mimetypeMimetype based on httpdocspythonorglibrarymimetypeshtml

gtgtgt fileobjectmimetype(imagejpeg None)

General Attributes

filetypeType of the file as defined with EXTENSIONS

gtgtgt fileobjectfiletypeImage

filesizeFilesize in Bytes

gtgtgt fileobjectfilesize870037L

14 Chapter 2 API

Django FileBrowser Documentation Release 357

dateDate based on timemktime

gtgtgt fileobjectdate12997603470

datetimeDatetime object

gtgtgt fileobjectdatetimedatetimedatetime(2011 3 10 13 32 27)

existsTrue if the path exists False otherwise

gtgtgt fileobjectexistsTrue

Path and URL attributes

pathPath relative to a storage location (including sitedirectory)

gtgtgt fileobjectpathuploadstestfoldertestimagejpg

path_relative_directoryPath relative to sitedirectory

gtgtgt fileobjectpath_relative_directorytestfoldertestimagejpg

path_fullAbsolute server path (based on storagepath)

gtgtgt fileobjectpath_fullabsolutepathtoserverlocationtestfoldertestimagejpg

dirnameNew in version 34

The directory (not including sitedirectory)

gtgtgt fileobjectdirnametestfolder

urlURL for the filefolder (based on storageurl)

gtgtgt fileobjecturlmediauploadstestfoldertestimagejpg

Image attributes

The image attributes are only useful if the FileObject represents an image

dimensionsImage dimensions as a tuple

21 API 15

Django FileBrowser Documentation Release 357

gtgtgt fileobjectdimensions(1000 750)

widthImage width in px

gtgtgt fileobjectwidth1000

heightImage height in px

gtgtgt fileobjectheight750

aspectratioAspect ratio (float format)

gtgtgt fileobjectaspectratio133534908

orientationImage orientation either Landscape or Portrait

gtgtgt fileobjectorientationLandscape

Folder attributes

The folder attributes make sense when the FileObject represents a directory (not a file)

directory

Deprecated since version 353 Use path_relative_directory instead

folder

Deprecated since version 353 Use dirname instead

is_folderTrue if path is a folder

gtgtgt fileobjectis_folderFalse

is_emptyTrue if the folder is empty False if the folder is not empty or the FileObject is not a folder

gtgtgt fileobjectis_emptyFalse

Version attributes

is_versiontrue if the File is a version of another File

16 Chapter 2 API

Django FileBrowser Documentation Release 357

gtgtgt fileobjectis_versionFalsegtgtgt versionis_versionTrue

versions_basedirThe relative path (from storage location) to the main versions folder Either VERSIONS_BASEDIR orsitedirectory

gtgtgt fileobjectversions_basedir_versionsgtgtgt versionversions_basedir_versions

originalReturns the original FileObject

gtgtgt fileobjectoriginalltFileObject uploadstestfoldertestimagejpggtgtgtgt versionoriginalltFileObject uploadstestfoldertestimagejpggt

original_filenameGet the filename of an original image from a version

gtgtgt fileobjectoriginal_filenametestimagejpggtgtgt versionoriginal_filenametestimagejpg

Methods

Version methods

versions()List all filenames based on VERSIONS

gtgtgt fileobjectversions()[_versionstestfoldertestimage_admin_thumbnailjpg_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionversions()[]

Note The versions are not being generated

admin_versions()List all filenames based on ADMIN_VERSIONS

gtgtgt fileobjectadmin_versions()[_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg

21 API 17

Django FileBrowser Documentation Release 357

_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionadmin_versions()[]

Note The versions are not being generated

version_name(version_suffix)Get the filename for a version

gtgtgt fileobjectversion_name(medium)testimage_mediumjpg

Note The version is not being generated

version_path(version_suffix)Get the path for a version

gtgtgt fileobjectversion_path(medium)_versionstestfoldertestimage_mediumjpg

Note The version is not being generated

version_generate(version_suffix)Generate a version

gtgtgt fileobjectversion_generate(medium)ltFileObject uploadstestfoldertestimage_mediumjpggt

Please note that a version is only generated if it does not already exist or if the original image is newer than theexisting version

Delete methods

delete()Delete the File or Folder from the server

Warning If you delete a Folder all items within the folder are being deleted

delete_versions()Delete all VERSIONS

delete_admin_versions()Delete all ADMIN_VERSIONS

18 Chapter 2 API

CHAPTER 3

Fields amp Widgets

31 Fields amp Widgets

The FileBrowseField is a custom model field which returns a FileObject The widgets FileInput and ClearableFileIn-put are used with the admin app in order to show an additional thumbnail for images

311 FileBrowseField

class FileBrowseField(max_length[ site directory extensions format options])A subclass of CharField referencing a media file within Returns a FileObject

Parameters

bull site ndash A FileBrowser site (defaults to the main site) see FileBrowser Site

bull directory ndash Directory to browse when clicking the search icon

bull extensions ndash List of allowed extensions see Extensions and Formats

bull format ndash A key from SELECT_FORMATS in order to restrict the selection to specificfiletypes see Extensions and Formats

For example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 directory=images extensions=[jpg] blank=True null=True)document = FileBrowseField(PDF max_length=200 directory=documents extensions=[pdfdoc] blank=True null=True)

FileBrowseField in Templates

You can use all attributes from FileObject

blogentryimage ltimg src= publicationimageurl gt

ifequal blogentryimageimage_orientation landscape ltimg src= blogentryimageurl class=landscape gt

endifequal

19

Django FileBrowser Documentation Release 357

Showing Thumbnail in the Changelist

To show a thumbnail with the changelist you can define a ModelAdmin method

from filebrowsersettings import ADMIN_THUMBNAIL

def image_thumbnail(self obj)if objimage and objimagefiletype == Image

return ltimg src=s gt objimageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Using the FileBrowseField with TinyMCE

In order to replace the TinyMCE imagefile manager with the FileBrowser you have to use a FileBrowser CallbackTherersquos an example TinyMCE configuration file in staticjs called TinyMCEAdminjs You can either copy theFileBrowserCallback to your own file or just use tinymce_setupjs (which comes with django-grappelli)

Just add these lines to your ModelAdmin asset definitions

class Mediajs = [pathtotinymcejscriptstiny_mcetiny_mcejs

pathtoyourtinymce_setupjs]

312 FileInput

Subclass of FileInput with an additional thumbnail

from filebrowserwidgets import FileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget FileInput

313 ClearableFileInput

Subclass of ClearableFileInput with an additional thumbnail

from filebrowserwidgets import ClearableFileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget ClearableFileInput

314 Django FileField and the FileBrowser

Return a FileObject from a FileField or ImageField with

20 Chapter 3 Fields amp Widgets

Django FileBrowser Documentation Release 357

from filebrowserbase import FileObject

image_upload = modelsImageField(uImage (Upload) max_length=250 upload_to=image_upload_path blank=True null=True)

def image(self)if selfimage_upload

return FileObject(selfimage_uploadpath)return None

In order show a thumbnail with your changelist you could use a ModelAdmin method

from filebrowserbase import FileObject

def image_thumbnail(self obj)if objimage_upload

image = FileObject(objimage_uploadpath)if imagefiletype == Image

return ltimg src=s gt imageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Note There are different ways to achieve this The above examples show one of several options

31 Fields amp Widgets 21

Django FileBrowser Documentation Release 357

22 Chapter 3 Fields amp Widgets

CHAPTER 4

Admin Interface

41 Admin Interface

The main FileBrowser admin application is an extension for the Django admin interface in order to browser yourmedia folder upload and renamedelete files

411 FileBrowser Site

New in version 340

class FileBrowserSite(name=None app_name=rsquofilebrowserrsquo storage=default_storage)Respresents the FileBrowser admin application (similar to Djangorsquos admin site)

Parameters

bull name ndash A name for the site defaults to None

bull app_name ndash Defaults to lsquofilebrowserrsquo

bull storage ndash A custom storage engine defaults to Djangos default storage

Similar to djangocontribadmin you first need to add a filebrowsersite to your admin interface Inyour urlspy import the default FileBrowser site (or your custom site) and add the site to your URL-patterns (beforeany admin-urls)

from filebrowsersites import site

urlpatterns = patterns(url(r^adminurlfilebrowser include(siteurls))

)

Now you are able to browse the location defined with the storage engine associated to your site

from djangocorefilesstorage import DefaultStoragefrom filebrowsersites import FileBrowserSite

Default FileBrowser sitesite = FileBrowserSite(name=filebrowser storage=DefaultStorage())

My Custom FileBrowser sitecustom_site = FileBrowserSite(name=custom_filebrowser storage=DefaultStorage())custom_sitedirectory = custom_uploads

23

Django FileBrowser Documentation Release 357

Note The module variable site from filebrowsersites is the default FileBrowser application

412 Custom Actions

New in version 340

Similar to Djangorsquos admin actions you can define your FileBrowser actions and thus automate the typical tasks ofyour users Registered custom actions are listed in the detail view of a file and a user can select a single action at atime The selected action will then be applied to the file

The default FileBrowser image actions such as ldquoFlip Verticalrdquo or ldquoRotate 90deg Clockwiserdquo are in fact implemented ascustom actions (see the module filebrowseractions)

Writing Your Own Actions

Custom actions are simple functions

def foo(request fileobjects) Do something with the fileobjects

The first parameter is a HttpRequest object (representing the submitted form in which a user selected the action)and the second parameter is a list of FileObjects to which the action should be applied

The list contains exactly one instance of FileObject (representing the file from the detail view) but this may change inthe future as custom actions may become available also in browse views (similar to admin actions applied to a list ofchecked objects)

Registering an Action

In order to make your action visible you need to register it with a FileBrowser site

siteadd_action(foo)

Once registered the action will appear in the detail view of a file You can also give your action a short description

fooshort_description = Do foo with the File

This short description will then appear in the list of available actions If you do not provide a short description thefunction name will be used instead and FileBrowser will replace any underscores in the function name with spaces

Associating Actions with Specific Files

Each custom action can be associated with a specific file type (eg images audio file etc) to which it applies In orderto do that you need to define a predicatefilter function which takes a single argument (FileObject) and returns Trueif your action is applicable to that FileObject Finally you need to register this filter function with your action

fooapplies_to(lambda fileobject fileobjectfiletype == Image)

In the above example foo will appear in the action list only for image files If you do not specify any filter functionfor your action FileBrowser considers the action as applicable to all files

24 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

Messages amp Intermediate Pages

You can provide a feedback to a user about a successful or failed execution of an action by using a message Forexample

from djangocontrib import messages

def desaturate_image(request fileobjects)for f in fileobjects

Desaturate the imagemessagesadd_message(request messagesSUCCESS _(Image s was desaturated) ffilename)

Some actions may require user confirmation (eg in order to prevent accidental and irreversible modification tofiles) In order to that follow the same pattern as with Djangorsquos admin action and return a HttpResponse objectfrom your action Good practice for intermediate pages is to implement a confirm view and have your action returnHttpResponseRedirect

def crop_image(request fileobjects)files = ampf=join([fpath_relative for f in fileobjects])return HttpResponseRedirect(confirmaction=crop_imageampf=s files)

413 File Storages

New in version 340

You have the option to specify which file storage engine a FileBrowser should use to browseuploadmodify yourmedia files This enables you to use a FileBrowser even if your media files are located at some remote system Seealso the Djangorsquos documentation on storages httpsdocsdjangoprojectcomendevtopicsfiles

To associate a FileBrowser site with a particular storage engine set the storage property of a site object

from djangocorefilesstorage import FileSystemStoragesitestorage = FileSystemStorage(location=pathtomediadirectory base_url=media)

For storage classes other than FileSystemStorage (or those that inherit from that class) therersquos more effort involved inproviding a storage object that can be used with FileBrowser See StorageMixin Class

Note Prior FileBrowser 34 the way to specify FileBrowserlsquos MEDIA_ROOT and MEDIA_URL was via settingspyStarting from version 34 those variables are associated with the storage instance and you can set them as illustratedin the above example

Warning For the reason of backward compatibility FileBrowser settings FILEBROWSER_MEDIA_ROOT andFILEBROWSER_MEDIA_URL can still be used to customize FileBrowser as long as yoursquore using the defaultFileBrowserlsquos site without having changed its storage engine In the next major release of FileBrowser thesesettings will be removed

StorageMixin Class

A FileBrowser uses the Djangorsquos Storage class to access media files However the API of the Storageclass does not provide all methods necessary for FileBrowserrsquos functionality A StorageMixin class fromfilebrowserstorage module therefore defines all the additional methods that a FileBrowser requires

isdir(self name)Returns true if name exists and is a directory

41 Admin Interface 25

Django FileBrowser Documentation Release 357

isfile(self name)Returns true if name exists and is a regular file

move(self old_file_name new_file_name allow_overwrite=False)Moves safely a file from one location to another If allow_ovewrite==False and new_file_nameexists raises an exception

makedirs(self name)Creates all missing directories specified by name Analogue to osmkdirs()

414 Views

All views use the staff_member_requird and path_exists decorator in order to check if the server pathactually exists Some views also use the file_exists decorator

bull Browse fb_browse Browse a directory on your server Returns a FileListing

ndash Optional query string args dir o ot q p filter_date filter_type type

bull Create directory fb_createdir Create a new folder on your server

ndash Optional query string args dir

ndash Signals filebrowser_pre_createdir filebrowser_post_createdir

bull Upload fb_upload Multiple upload

ndash Optional query string args dir type

ndash Signals filebrowser_pre_upload filebrowser_post_upload

bull Edit fb_edit Edit a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_rename filebrowser_post_rename

You are able to apply custom actions (see Custom Actions) to the edit-view

bull Confirm delete fb_confirm_delete Confirm the deletion of a file or folder

ndash Required query string args filename

ndash Optional query string args dir

If you try to delete a folder all filesfolders within this folder are listed on this page

bull Delete fb_delete Delete a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_delete filebrowser_post_delete

Warning If you delete a Folder all items within this Folder are being deleted

bull Version fb_version Generate a version of an image as defined with ADMIN_VERSIONS

ndash Required query string args filename

ndash Optional Query string args dir

This is a helper used by the FileBrowseField and TinyMCE for selecting a version

26 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

415 Signals

The FileBrowser sends a couple of different signals Please take a look at the module filebrowsersignals for furtherexplanation on the provided arguments

bull filebrowser_pre_upload Sent before a an Upload starts

bull filebrowser_post_upload Sent after an Upload has finished

bull filebrowser_pre_delete Sent before an Item (File Folder) is deleted

bull filebrowser_post_delete Sent after an Item (File Folder) has been deleted

bull filebrowser_pre_createdir Sent before a new Folder is created

bull filebrowser_post_createdir Sent after a new Folder has been created

bull filebrowser_pre_rename Sent before an Item (File Folder) is renamed

bull filebrowser_post_rename Sent after an Item (File Folder) has been renamed

bull filebrowser_actions_pre_apply Sent before a custom action is applied

bull filebrowser_actions_post_apply Sent after a custom action has been applied

Example for using these Signals

Herersquos a small example for using the above Signals

from filebrowser import signals

def pre_upload_callback(sender kwargs)Receiver function called before an upload startsprint Pre Upload Callbackprint kwargs kwargs

signalsfilebrowser_pre_uploadconnect(pre_upload_callback)

def post_upload_callback(sender kwargs)Receiver function called each time an upload has finishedprint Post Upload Callbackprint kwargs kwargs You can use all attributes available with the FileObject This is just an example print Filesize kwargs[file]filesizeprint Orientation kwargs[file]orientationprint Extension kwargs[file]extension

signalsfilebrowser_post_uploadconnect(post_upload_callback)

41 Admin Interface 27

Django FileBrowser Documentation Release 357

28 Chapter 4 Admin Interface

CHAPTER 5

Image Versions

51 Versions

With the FileBrowser you are able to define different versionssizes for images This enables you to save an originalimage on your server while having different versions of that image to automatically fit your websites grid Versionsare also useful for responsiveadaptive layouts

511 Defining Versions

New in version 340 methods

First you need to know which versionssizes of an image yoursquod like to generate with your website Letrsquos say yoursquoreusing a 12 column grid with 60px for each column and 20px margin (which is a total of 940px) With this grid youcould (for example) define these image versions

FILEBROWSER_VERSIONS_BASEDIR = _versionsFILEBROWSER_VERSIONS =

admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

Use the methods argument if you need to add a filter

def grayscale(im)Convert image to grayscaleif immode = L

im = imconvert(L)return im

FILEBROWSER_VERSIONS = big verbose_name Big (6 col) width 460 height opts methods [grayscale]

)

29

Django FileBrowser Documentation Release 357

512 Versions and the Admin

When using the FileBrowser with the admin interface you need to define ADMIN_VERSIONS andADMIN_THUMBNAIL (see Settings) ADMIN_VERSIONS are available with the admin ie you are able to seethese versions with the image detail view and you are able to select the versions with the FileBrowseField model field

FILEBROWSER_ADMIN_VERSIONS = [thumbnail small medium big large]FILEBROWSER_ADMIN_THUMBNAIL = admin_thumbnail

513 Versions and the Frontend

With your templates you have two different tags to choose from version and version_object With bothtags the version will be generated if it doesnrsquot already exist OR if the original image is newer than the version Inorder to update an image you just overwrite the original image and the versions will be generated automatically (asyou request them within your template)

A Model example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 blank=True null=True)

With your templates use version if you simply need to retrieve the URL or version_object if you need to geta FileObject

lt-- load filebrowser templatetags --gt load fb_versions

lt-- get the url with version --gtltimg src= version blogentryimage medium gt

lt-- get a fileobject with version_object --gt version_object blogentryimage medium as version_medium version_mediumwidth ltimg src= version_medium gt

Templatetag version

RetrievesGenerates a version and returns an URL

version modelfield_name version_prefix

Templatetag version_object

RetrievesGenerates a version and returns a FileObject

version_object modelfield_name version_prefix as variable

Note With both templatetags version_prefix can either be a string or a variable If version_prefix is astring use quotes

30 Chapter 5 Image Versions

Django FileBrowser Documentation Release 357

514 Versions in Views

If you have a FileObject you can generateretrieve a version with

v = objimageversion_generate(version_prefix) returns a FileObject

515 Placeholder

When developing on a locale machine or a development-server you might not have all the images (resp media-files)available that are on your production instance and downloading these files on a regular basis might not be an option

In that case you can use a placeholder instead of a version You just need to define the PLACEHOLDER and overwritethe settings SHOW_PLACEHOLDER andor FORCE_PLACEHOLDER (see Placeholder)

516 Management Commands

fb_version_generateIf you need to generate certain (or all) versions type

python managepy fb_version_generate

fb_version_removeIf you need to generate certain (or all) versions type

python managepy fb_version_generate

Warning Please be very careful with this command

51 Versions 31

Django FileBrowser Documentation Release 357

32 Chapter 5 Image Versions

CHAPTER 6

Help

61 Help

611 FAQ

Why should I use the FileBrowser

If you need your editors or customers to manage files the FileBrowser is an alternative to an FTP-client Moreoveryou are able to define different image versions according to your websites grid Alternatives to the FileBrowser can befound at httpdjangopackagescomgridsgfile-managers

Do I need Grappelli

Grappelli is a requirement for using the FileBrowser There are several filebrowser-no-grappelli repositories (most ofthem on GitHub) but we donrsquot follow the development

I need help

see Troubleshooting

Why are there no fancy effects

The FileBrowser is about managing files We think that you should prepare your files before uploading them to theserver

How do I upload to another server

Use a custom storage engine see httpsdocsdjangoprojectcomen16howtocustom-file-storage

Why do I need image-versions

You need image-versions if your website is based on a grid

33

Django FileBrowser Documentation Release 357

Is the FileBrowser stable

Wersquove developed the FileBrowser for a couple of years and use it with almost all of our clients That said Grappelli isthe more stable and mature application

How can I contribute

Help is very much needed and appreciated Test the FileBrowser and submit feedbackpatches

Who develops the FileBrowser

The FileBrowser is developed and maintained by Patrick Kranzlmuumlller amp Axel Swoboda of vonautomatisch

612 Troubleshooting

Check your setup

Please check if the problem is caused by your setup

bull Read Quick start guide

bull Check if the staticmedia-files are served correctly

bull Make sure you have removed all custom FileBrowser templates from all locations in TEMPLATE_DIRS orcheck that these templates are compatible with the FileBrowser

Run the tests

Start the shell and type

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Check issues

If your setup is fine please check if your problem is a known issue

bull Take a look at all FileBrowser Issues (incuding closed) and search the FileBrowser Google-Group

Add a ticket

If you think yoursquove found a bug please add a ticket

bull Try to describe your problem as precisely as possible

bull Tell us what you did in order to solve the problem

bull Tell us what version of the FileBrowser you are using

bull Tell us what version of Django you are using

34 Chapter 6 Help

Django FileBrowser Documentation Release 357

bull Please do NOT add tickets if yoursquore having problems with serving staticmedia-files (because this is not relatedto the FileBrowser)

bull Please do NOT add tickets referring to Djangos trunk version

bull At best add a patch

Note Be aware that we may close issues not following these guidlines without further notifications

613 Translation

Translation is done via Transifex

Supported Languages

see httpswwwtransifexnetprojectspdjango-filebrowserresourcedjangopo

614 FileBrowser 35 Release Notes

FileBrowser 35 is compatible with Django 14151617 as well as Grappelli 242526

Update from FileBrowser 34x

bull Update Django to 14151617 and check httpsdocsdjangoprojectcomendevreleases14 orhttpsdocsdjangoprojectcomendevreleases15 or httpsdocsdjangoprojectcomendevreleases16

bull Update Grappelli to 24x25x26x

bull Update FileBrowser to 35x

62 Changelog

621 358 (not yet released)

622 357 (September 10th 2014)

bull New Compatibility with Django 17 and Grappelli 26x

bull Improved Updated tests because of the new random suffix with get_available_name (django storage)

bull Improved Added an icon in order to mark finished uploads

bull Improved Show resulting filename (eg with suffix converted) after successful upload

bull Fixed Permissions with file upload

bull Fixed Unified json response with _upload_file (no matter if file already exists or not)

623 356 (April 16th 2014)

bull Fixed Displaying pagination correctly with lots of entries

62 Changelog 35

Django FileBrowser Documentation Release 357

624 355 (April 13th 2014)

bull New Added client-side (JavaScript) file extension validation to the AJAX uploader

bull New Added experimental Python 33 support

bull Improved Tests with convertnormalize (removed special chars from test filename)

bull Fixed File selection after using search box (CKEditor)

bull Fixed Removed encoding of file URIs with CKEditor

625 354 (February 21st 2014)

bull Fixed Placeholder functionality (including tests)

bull Fixed Convertnormalize filenames (including tests)

bull Fixed Handling uppercase extensions with browse

626 353 (January 7 2014)

bull New added path_full to FileObject

bull Improved added docx to EXTENSIONS

bull Improved Recommend pillow instead of PIL as a requirement

bull Improved Added additional test cases

bull Improved Updated documentation

bull Improved Consistent use of storage (eg storagelocation storageurl)

bull Improved Removed unnecessary functions (eg url_join url_strip)

bull Improved Moved sort_by_attr to FileListing

bull Improved Regex matches with file versions on browse

bull Improved Using djangoconfurls (with djangoconfurlsdefaults as fallback)

bull Improved Adding CONTRIBUTINGrst

bull Improved Removed static Media inner class with fields

bull Improved Removed search icon with fields (has not being used)

bull Improved Added custom class attributes with filebrowser field

bull Improved Updated translations

bull Fixed fixed exception handling with python 25

bull Fixed fixes dir with SEARCH_TRAVERSE true and version select

bull Fixed Make Django FileUploadHandlers work (also fixed a memory leak)

bull Fixed return correct filename with OVERWRITE_EXISTING

bull Fixed fb_version_generate with FILEBROWSER_VERSIONS_BASEDIR

bull Fixed Table sorting with ascdesc

bull Fixed Added DeprecationWarning for FileObjectdirectory and FileObjectfolder

36 Chapter 6 Help

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

Django FileBrowser Documentation Release 357

listing()Returns all items for the given path with oslistdir(path)

gtgtgt for item in filelistinglisting() print itemblogtestfolder

walk()Returns all items for the given path with oswalk(path)

gtgtgt for item in filelistingwalk() print itemblogblog1blog1imagesblog1imagesblogimagejpgblog1imagesblogimage_admin_thumbnailjpgblog1imagesblogimage_mediumjpgblog1imagesblogimage_smalljpgblog1imagesblogimage_thumbnailjpgtestfoldertestfoldertestimagejpg

files_listing_total()Returns a sorted list of FileObjects for listing()

gtgtgt for item in filelistingfiles_listing_total() print itemuploadsbloguploadstestfolder

files_walk_total()Returns a sorted list of FileObjects for walk()

gtgtgt for item in filelistingfiles_walk_total() print itemuploadsbloguploadsblog1uploadsblog1imagesuploadsblog1imagesblogimagejpguploadsblog1imagesblogimage_admin_thumbnailjpguploadsblog1imagesblogimage_mediumjpguploadsblog1imagesblogimage_smalljpguploadsblog1imagesblogimage_thumbnailjpguploadstestfolderuploadstestfoldertestimagejpg

files_listing_filtered()Returns a sorted and filtered list of FileObjects for listing()

gtgtgt for item in filelistingfiles_listing_filtered() print itemuploadsbloguploadstestfolder

files_walk_filtered()Returns a sorted and filtered list of FileObjects for walk()

12 Chapter 2 API

Django FileBrowser Documentation Release 357

gtgtgt for item in filelistingfiles_walk_filtered() print itemuploadsbloguploadsblog1uploadsblog1imagesuploadsblog1imagesblogimagejpguploadstestfolderuploadstestfoldertestimagejpg

Note The versions are not listed (compared with files_walk_total) because of filter_func

results_listing_total()Number of total files based on files_listing_total()

gtgtgt filelistingresults_listing_total()2

results_walk_total()Number of total files based on files_walk_total()

gtgtgt filelistingresults_walk_total()10

results_listing_filtered()Number of filtered files based on files_listing_filtered()

gtgtgt filelistingresults_listing_filtered()2

results_walk_filtered()Number of filtered files based on files_walk_filtered()

gtgtgt filelistingresults_walk_filtered()6

212 FileObject

class FileObject(path site=None)An object representing a media file

Parameters

bull path ndash Relative path to a location within sitestoragelocation

bull site ndash An optional FileBrowser Site

For example

from filebrowsersites import sitefrom filebrowserbase import FileObjectfileobject = FileObject(ospathjoin(sitedirectorytestfoldertestimagejpg))version = FileObject(ospathjoin(fileobjectversions_basedir testfolder testimage_mediumjpg))

21 API 13

Django FileBrowser Documentation Release 357

Attributes

Initial Attributes

pathPath relative to a storage location (including sitedirectory)

gtgtgt fileobjectpathuploadstestfoldertestimagejpg

headThe directory name of pathname path

gtgtgt fileobjectheaduploadstestfolder

filenameName of the file (including the extension) or name of the folder

gtgtgt fileobjectfilenametestimagejpg

filename_lowerLower type of filename

filename_rootFilename without extension

gtgtgt fileobjectfilename_roottestimage

extensionFile extension including the dot With a folder the extensions is None

gtgtgt fileobjectextensionjpg

mimetypeMimetype based on httpdocspythonorglibrarymimetypeshtml

gtgtgt fileobjectmimetype(imagejpeg None)

General Attributes

filetypeType of the file as defined with EXTENSIONS

gtgtgt fileobjectfiletypeImage

filesizeFilesize in Bytes

gtgtgt fileobjectfilesize870037L

14 Chapter 2 API

Django FileBrowser Documentation Release 357

dateDate based on timemktime

gtgtgt fileobjectdate12997603470

datetimeDatetime object

gtgtgt fileobjectdatetimedatetimedatetime(2011 3 10 13 32 27)

existsTrue if the path exists False otherwise

gtgtgt fileobjectexistsTrue

Path and URL attributes

pathPath relative to a storage location (including sitedirectory)

gtgtgt fileobjectpathuploadstestfoldertestimagejpg

path_relative_directoryPath relative to sitedirectory

gtgtgt fileobjectpath_relative_directorytestfoldertestimagejpg

path_fullAbsolute server path (based on storagepath)

gtgtgt fileobjectpath_fullabsolutepathtoserverlocationtestfoldertestimagejpg

dirnameNew in version 34

The directory (not including sitedirectory)

gtgtgt fileobjectdirnametestfolder

urlURL for the filefolder (based on storageurl)

gtgtgt fileobjecturlmediauploadstestfoldertestimagejpg

Image attributes

The image attributes are only useful if the FileObject represents an image

dimensionsImage dimensions as a tuple

21 API 15

Django FileBrowser Documentation Release 357

gtgtgt fileobjectdimensions(1000 750)

widthImage width in px

gtgtgt fileobjectwidth1000

heightImage height in px

gtgtgt fileobjectheight750

aspectratioAspect ratio (float format)

gtgtgt fileobjectaspectratio133534908

orientationImage orientation either Landscape or Portrait

gtgtgt fileobjectorientationLandscape

Folder attributes

The folder attributes make sense when the FileObject represents a directory (not a file)

directory

Deprecated since version 353 Use path_relative_directory instead

folder

Deprecated since version 353 Use dirname instead

is_folderTrue if path is a folder

gtgtgt fileobjectis_folderFalse

is_emptyTrue if the folder is empty False if the folder is not empty or the FileObject is not a folder

gtgtgt fileobjectis_emptyFalse

Version attributes

is_versiontrue if the File is a version of another File

16 Chapter 2 API

Django FileBrowser Documentation Release 357

gtgtgt fileobjectis_versionFalsegtgtgt versionis_versionTrue

versions_basedirThe relative path (from storage location) to the main versions folder Either VERSIONS_BASEDIR orsitedirectory

gtgtgt fileobjectversions_basedir_versionsgtgtgt versionversions_basedir_versions

originalReturns the original FileObject

gtgtgt fileobjectoriginalltFileObject uploadstestfoldertestimagejpggtgtgtgt versionoriginalltFileObject uploadstestfoldertestimagejpggt

original_filenameGet the filename of an original image from a version

gtgtgt fileobjectoriginal_filenametestimagejpggtgtgt versionoriginal_filenametestimagejpg

Methods

Version methods

versions()List all filenames based on VERSIONS

gtgtgt fileobjectversions()[_versionstestfoldertestimage_admin_thumbnailjpg_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionversions()[]

Note The versions are not being generated

admin_versions()List all filenames based on ADMIN_VERSIONS

gtgtgt fileobjectadmin_versions()[_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg

21 API 17

Django FileBrowser Documentation Release 357

_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionadmin_versions()[]

Note The versions are not being generated

version_name(version_suffix)Get the filename for a version

gtgtgt fileobjectversion_name(medium)testimage_mediumjpg

Note The version is not being generated

version_path(version_suffix)Get the path for a version

gtgtgt fileobjectversion_path(medium)_versionstestfoldertestimage_mediumjpg

Note The version is not being generated

version_generate(version_suffix)Generate a version

gtgtgt fileobjectversion_generate(medium)ltFileObject uploadstestfoldertestimage_mediumjpggt

Please note that a version is only generated if it does not already exist or if the original image is newer than theexisting version

Delete methods

delete()Delete the File or Folder from the server

Warning If you delete a Folder all items within the folder are being deleted

delete_versions()Delete all VERSIONS

delete_admin_versions()Delete all ADMIN_VERSIONS

18 Chapter 2 API

CHAPTER 3

Fields amp Widgets

31 Fields amp Widgets

The FileBrowseField is a custom model field which returns a FileObject The widgets FileInput and ClearableFileIn-put are used with the admin app in order to show an additional thumbnail for images

311 FileBrowseField

class FileBrowseField(max_length[ site directory extensions format options])A subclass of CharField referencing a media file within Returns a FileObject

Parameters

bull site ndash A FileBrowser site (defaults to the main site) see FileBrowser Site

bull directory ndash Directory to browse when clicking the search icon

bull extensions ndash List of allowed extensions see Extensions and Formats

bull format ndash A key from SELECT_FORMATS in order to restrict the selection to specificfiletypes see Extensions and Formats

For example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 directory=images extensions=[jpg] blank=True null=True)document = FileBrowseField(PDF max_length=200 directory=documents extensions=[pdfdoc] blank=True null=True)

FileBrowseField in Templates

You can use all attributes from FileObject

blogentryimage ltimg src= publicationimageurl gt

ifequal blogentryimageimage_orientation landscape ltimg src= blogentryimageurl class=landscape gt

endifequal

19

Django FileBrowser Documentation Release 357

Showing Thumbnail in the Changelist

To show a thumbnail with the changelist you can define a ModelAdmin method

from filebrowsersettings import ADMIN_THUMBNAIL

def image_thumbnail(self obj)if objimage and objimagefiletype == Image

return ltimg src=s gt objimageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Using the FileBrowseField with TinyMCE

In order to replace the TinyMCE imagefile manager with the FileBrowser you have to use a FileBrowser CallbackTherersquos an example TinyMCE configuration file in staticjs called TinyMCEAdminjs You can either copy theFileBrowserCallback to your own file or just use tinymce_setupjs (which comes with django-grappelli)

Just add these lines to your ModelAdmin asset definitions

class Mediajs = [pathtotinymcejscriptstiny_mcetiny_mcejs

pathtoyourtinymce_setupjs]

312 FileInput

Subclass of FileInput with an additional thumbnail

from filebrowserwidgets import FileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget FileInput

313 ClearableFileInput

Subclass of ClearableFileInput with an additional thumbnail

from filebrowserwidgets import ClearableFileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget ClearableFileInput

314 Django FileField and the FileBrowser

Return a FileObject from a FileField or ImageField with

20 Chapter 3 Fields amp Widgets

Django FileBrowser Documentation Release 357

from filebrowserbase import FileObject

image_upload = modelsImageField(uImage (Upload) max_length=250 upload_to=image_upload_path blank=True null=True)

def image(self)if selfimage_upload

return FileObject(selfimage_uploadpath)return None

In order show a thumbnail with your changelist you could use a ModelAdmin method

from filebrowserbase import FileObject

def image_thumbnail(self obj)if objimage_upload

image = FileObject(objimage_uploadpath)if imagefiletype == Image

return ltimg src=s gt imageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Note There are different ways to achieve this The above examples show one of several options

31 Fields amp Widgets 21

Django FileBrowser Documentation Release 357

22 Chapter 3 Fields amp Widgets

CHAPTER 4

Admin Interface

41 Admin Interface

The main FileBrowser admin application is an extension for the Django admin interface in order to browser yourmedia folder upload and renamedelete files

411 FileBrowser Site

New in version 340

class FileBrowserSite(name=None app_name=rsquofilebrowserrsquo storage=default_storage)Respresents the FileBrowser admin application (similar to Djangorsquos admin site)

Parameters

bull name ndash A name for the site defaults to None

bull app_name ndash Defaults to lsquofilebrowserrsquo

bull storage ndash A custom storage engine defaults to Djangos default storage

Similar to djangocontribadmin you first need to add a filebrowsersite to your admin interface Inyour urlspy import the default FileBrowser site (or your custom site) and add the site to your URL-patterns (beforeany admin-urls)

from filebrowsersites import site

urlpatterns = patterns(url(r^adminurlfilebrowser include(siteurls))

)

Now you are able to browse the location defined with the storage engine associated to your site

from djangocorefilesstorage import DefaultStoragefrom filebrowsersites import FileBrowserSite

Default FileBrowser sitesite = FileBrowserSite(name=filebrowser storage=DefaultStorage())

My Custom FileBrowser sitecustom_site = FileBrowserSite(name=custom_filebrowser storage=DefaultStorage())custom_sitedirectory = custom_uploads

23

Django FileBrowser Documentation Release 357

Note The module variable site from filebrowsersites is the default FileBrowser application

412 Custom Actions

New in version 340

Similar to Djangorsquos admin actions you can define your FileBrowser actions and thus automate the typical tasks ofyour users Registered custom actions are listed in the detail view of a file and a user can select a single action at atime The selected action will then be applied to the file

The default FileBrowser image actions such as ldquoFlip Verticalrdquo or ldquoRotate 90deg Clockwiserdquo are in fact implemented ascustom actions (see the module filebrowseractions)

Writing Your Own Actions

Custom actions are simple functions

def foo(request fileobjects) Do something with the fileobjects

The first parameter is a HttpRequest object (representing the submitted form in which a user selected the action)and the second parameter is a list of FileObjects to which the action should be applied

The list contains exactly one instance of FileObject (representing the file from the detail view) but this may change inthe future as custom actions may become available also in browse views (similar to admin actions applied to a list ofchecked objects)

Registering an Action

In order to make your action visible you need to register it with a FileBrowser site

siteadd_action(foo)

Once registered the action will appear in the detail view of a file You can also give your action a short description

fooshort_description = Do foo with the File

This short description will then appear in the list of available actions If you do not provide a short description thefunction name will be used instead and FileBrowser will replace any underscores in the function name with spaces

Associating Actions with Specific Files

Each custom action can be associated with a specific file type (eg images audio file etc) to which it applies In orderto do that you need to define a predicatefilter function which takes a single argument (FileObject) and returns Trueif your action is applicable to that FileObject Finally you need to register this filter function with your action

fooapplies_to(lambda fileobject fileobjectfiletype == Image)

In the above example foo will appear in the action list only for image files If you do not specify any filter functionfor your action FileBrowser considers the action as applicable to all files

24 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

Messages amp Intermediate Pages

You can provide a feedback to a user about a successful or failed execution of an action by using a message Forexample

from djangocontrib import messages

def desaturate_image(request fileobjects)for f in fileobjects

Desaturate the imagemessagesadd_message(request messagesSUCCESS _(Image s was desaturated) ffilename)

Some actions may require user confirmation (eg in order to prevent accidental and irreversible modification tofiles) In order to that follow the same pattern as with Djangorsquos admin action and return a HttpResponse objectfrom your action Good practice for intermediate pages is to implement a confirm view and have your action returnHttpResponseRedirect

def crop_image(request fileobjects)files = ampf=join([fpath_relative for f in fileobjects])return HttpResponseRedirect(confirmaction=crop_imageampf=s files)

413 File Storages

New in version 340

You have the option to specify which file storage engine a FileBrowser should use to browseuploadmodify yourmedia files This enables you to use a FileBrowser even if your media files are located at some remote system Seealso the Djangorsquos documentation on storages httpsdocsdjangoprojectcomendevtopicsfiles

To associate a FileBrowser site with a particular storage engine set the storage property of a site object

from djangocorefilesstorage import FileSystemStoragesitestorage = FileSystemStorage(location=pathtomediadirectory base_url=media)

For storage classes other than FileSystemStorage (or those that inherit from that class) therersquos more effort involved inproviding a storage object that can be used with FileBrowser See StorageMixin Class

Note Prior FileBrowser 34 the way to specify FileBrowserlsquos MEDIA_ROOT and MEDIA_URL was via settingspyStarting from version 34 those variables are associated with the storage instance and you can set them as illustratedin the above example

Warning For the reason of backward compatibility FileBrowser settings FILEBROWSER_MEDIA_ROOT andFILEBROWSER_MEDIA_URL can still be used to customize FileBrowser as long as yoursquore using the defaultFileBrowserlsquos site without having changed its storage engine In the next major release of FileBrowser thesesettings will be removed

StorageMixin Class

A FileBrowser uses the Djangorsquos Storage class to access media files However the API of the Storageclass does not provide all methods necessary for FileBrowserrsquos functionality A StorageMixin class fromfilebrowserstorage module therefore defines all the additional methods that a FileBrowser requires

isdir(self name)Returns true if name exists and is a directory

41 Admin Interface 25

Django FileBrowser Documentation Release 357

isfile(self name)Returns true if name exists and is a regular file

move(self old_file_name new_file_name allow_overwrite=False)Moves safely a file from one location to another If allow_ovewrite==False and new_file_nameexists raises an exception

makedirs(self name)Creates all missing directories specified by name Analogue to osmkdirs()

414 Views

All views use the staff_member_requird and path_exists decorator in order to check if the server pathactually exists Some views also use the file_exists decorator

bull Browse fb_browse Browse a directory on your server Returns a FileListing

ndash Optional query string args dir o ot q p filter_date filter_type type

bull Create directory fb_createdir Create a new folder on your server

ndash Optional query string args dir

ndash Signals filebrowser_pre_createdir filebrowser_post_createdir

bull Upload fb_upload Multiple upload

ndash Optional query string args dir type

ndash Signals filebrowser_pre_upload filebrowser_post_upload

bull Edit fb_edit Edit a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_rename filebrowser_post_rename

You are able to apply custom actions (see Custom Actions) to the edit-view

bull Confirm delete fb_confirm_delete Confirm the deletion of a file or folder

ndash Required query string args filename

ndash Optional query string args dir

If you try to delete a folder all filesfolders within this folder are listed on this page

bull Delete fb_delete Delete a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_delete filebrowser_post_delete

Warning If you delete a Folder all items within this Folder are being deleted

bull Version fb_version Generate a version of an image as defined with ADMIN_VERSIONS

ndash Required query string args filename

ndash Optional Query string args dir

This is a helper used by the FileBrowseField and TinyMCE for selecting a version

26 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

415 Signals

The FileBrowser sends a couple of different signals Please take a look at the module filebrowsersignals for furtherexplanation on the provided arguments

bull filebrowser_pre_upload Sent before a an Upload starts

bull filebrowser_post_upload Sent after an Upload has finished

bull filebrowser_pre_delete Sent before an Item (File Folder) is deleted

bull filebrowser_post_delete Sent after an Item (File Folder) has been deleted

bull filebrowser_pre_createdir Sent before a new Folder is created

bull filebrowser_post_createdir Sent after a new Folder has been created

bull filebrowser_pre_rename Sent before an Item (File Folder) is renamed

bull filebrowser_post_rename Sent after an Item (File Folder) has been renamed

bull filebrowser_actions_pre_apply Sent before a custom action is applied

bull filebrowser_actions_post_apply Sent after a custom action has been applied

Example for using these Signals

Herersquos a small example for using the above Signals

from filebrowser import signals

def pre_upload_callback(sender kwargs)Receiver function called before an upload startsprint Pre Upload Callbackprint kwargs kwargs

signalsfilebrowser_pre_uploadconnect(pre_upload_callback)

def post_upload_callback(sender kwargs)Receiver function called each time an upload has finishedprint Post Upload Callbackprint kwargs kwargs You can use all attributes available with the FileObject This is just an example print Filesize kwargs[file]filesizeprint Orientation kwargs[file]orientationprint Extension kwargs[file]extension

signalsfilebrowser_post_uploadconnect(post_upload_callback)

41 Admin Interface 27

Django FileBrowser Documentation Release 357

28 Chapter 4 Admin Interface

CHAPTER 5

Image Versions

51 Versions

With the FileBrowser you are able to define different versionssizes for images This enables you to save an originalimage on your server while having different versions of that image to automatically fit your websites grid Versionsare also useful for responsiveadaptive layouts

511 Defining Versions

New in version 340 methods

First you need to know which versionssizes of an image yoursquod like to generate with your website Letrsquos say yoursquoreusing a 12 column grid with 60px for each column and 20px margin (which is a total of 940px) With this grid youcould (for example) define these image versions

FILEBROWSER_VERSIONS_BASEDIR = _versionsFILEBROWSER_VERSIONS =

admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

Use the methods argument if you need to add a filter

def grayscale(im)Convert image to grayscaleif immode = L

im = imconvert(L)return im

FILEBROWSER_VERSIONS = big verbose_name Big (6 col) width 460 height opts methods [grayscale]

)

29

Django FileBrowser Documentation Release 357

512 Versions and the Admin

When using the FileBrowser with the admin interface you need to define ADMIN_VERSIONS andADMIN_THUMBNAIL (see Settings) ADMIN_VERSIONS are available with the admin ie you are able to seethese versions with the image detail view and you are able to select the versions with the FileBrowseField model field

FILEBROWSER_ADMIN_VERSIONS = [thumbnail small medium big large]FILEBROWSER_ADMIN_THUMBNAIL = admin_thumbnail

513 Versions and the Frontend

With your templates you have two different tags to choose from version and version_object With bothtags the version will be generated if it doesnrsquot already exist OR if the original image is newer than the version Inorder to update an image you just overwrite the original image and the versions will be generated automatically (asyou request them within your template)

A Model example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 blank=True null=True)

With your templates use version if you simply need to retrieve the URL or version_object if you need to geta FileObject

lt-- load filebrowser templatetags --gt load fb_versions

lt-- get the url with version --gtltimg src= version blogentryimage medium gt

lt-- get a fileobject with version_object --gt version_object blogentryimage medium as version_medium version_mediumwidth ltimg src= version_medium gt

Templatetag version

RetrievesGenerates a version and returns an URL

version modelfield_name version_prefix

Templatetag version_object

RetrievesGenerates a version and returns a FileObject

version_object modelfield_name version_prefix as variable

Note With both templatetags version_prefix can either be a string or a variable If version_prefix is astring use quotes

30 Chapter 5 Image Versions

Django FileBrowser Documentation Release 357

514 Versions in Views

If you have a FileObject you can generateretrieve a version with

v = objimageversion_generate(version_prefix) returns a FileObject

515 Placeholder

When developing on a locale machine or a development-server you might not have all the images (resp media-files)available that are on your production instance and downloading these files on a regular basis might not be an option

In that case you can use a placeholder instead of a version You just need to define the PLACEHOLDER and overwritethe settings SHOW_PLACEHOLDER andor FORCE_PLACEHOLDER (see Placeholder)

516 Management Commands

fb_version_generateIf you need to generate certain (or all) versions type

python managepy fb_version_generate

fb_version_removeIf you need to generate certain (or all) versions type

python managepy fb_version_generate

Warning Please be very careful with this command

51 Versions 31

Django FileBrowser Documentation Release 357

32 Chapter 5 Image Versions

CHAPTER 6

Help

61 Help

611 FAQ

Why should I use the FileBrowser

If you need your editors or customers to manage files the FileBrowser is an alternative to an FTP-client Moreoveryou are able to define different image versions according to your websites grid Alternatives to the FileBrowser can befound at httpdjangopackagescomgridsgfile-managers

Do I need Grappelli

Grappelli is a requirement for using the FileBrowser There are several filebrowser-no-grappelli repositories (most ofthem on GitHub) but we donrsquot follow the development

I need help

see Troubleshooting

Why are there no fancy effects

The FileBrowser is about managing files We think that you should prepare your files before uploading them to theserver

How do I upload to another server

Use a custom storage engine see httpsdocsdjangoprojectcomen16howtocustom-file-storage

Why do I need image-versions

You need image-versions if your website is based on a grid

33

Django FileBrowser Documentation Release 357

Is the FileBrowser stable

Wersquove developed the FileBrowser for a couple of years and use it with almost all of our clients That said Grappelli isthe more stable and mature application

How can I contribute

Help is very much needed and appreciated Test the FileBrowser and submit feedbackpatches

Who develops the FileBrowser

The FileBrowser is developed and maintained by Patrick Kranzlmuumlller amp Axel Swoboda of vonautomatisch

612 Troubleshooting

Check your setup

Please check if the problem is caused by your setup

bull Read Quick start guide

bull Check if the staticmedia-files are served correctly

bull Make sure you have removed all custom FileBrowser templates from all locations in TEMPLATE_DIRS orcheck that these templates are compatible with the FileBrowser

Run the tests

Start the shell and type

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Check issues

If your setup is fine please check if your problem is a known issue

bull Take a look at all FileBrowser Issues (incuding closed) and search the FileBrowser Google-Group

Add a ticket

If you think yoursquove found a bug please add a ticket

bull Try to describe your problem as precisely as possible

bull Tell us what you did in order to solve the problem

bull Tell us what version of the FileBrowser you are using

bull Tell us what version of Django you are using

34 Chapter 6 Help

Django FileBrowser Documentation Release 357

bull Please do NOT add tickets if yoursquore having problems with serving staticmedia-files (because this is not relatedto the FileBrowser)

bull Please do NOT add tickets referring to Djangos trunk version

bull At best add a patch

Note Be aware that we may close issues not following these guidlines without further notifications

613 Translation

Translation is done via Transifex

Supported Languages

see httpswwwtransifexnetprojectspdjango-filebrowserresourcedjangopo

614 FileBrowser 35 Release Notes

FileBrowser 35 is compatible with Django 14151617 as well as Grappelli 242526

Update from FileBrowser 34x

bull Update Django to 14151617 and check httpsdocsdjangoprojectcomendevreleases14 orhttpsdocsdjangoprojectcomendevreleases15 or httpsdocsdjangoprojectcomendevreleases16

bull Update Grappelli to 24x25x26x

bull Update FileBrowser to 35x

62 Changelog

621 358 (not yet released)

622 357 (September 10th 2014)

bull New Compatibility with Django 17 and Grappelli 26x

bull Improved Updated tests because of the new random suffix with get_available_name (django storage)

bull Improved Added an icon in order to mark finished uploads

bull Improved Show resulting filename (eg with suffix converted) after successful upload

bull Fixed Permissions with file upload

bull Fixed Unified json response with _upload_file (no matter if file already exists or not)

623 356 (April 16th 2014)

bull Fixed Displaying pagination correctly with lots of entries

62 Changelog 35

Django FileBrowser Documentation Release 357

624 355 (April 13th 2014)

bull New Added client-side (JavaScript) file extension validation to the AJAX uploader

bull New Added experimental Python 33 support

bull Improved Tests with convertnormalize (removed special chars from test filename)

bull Fixed File selection after using search box (CKEditor)

bull Fixed Removed encoding of file URIs with CKEditor

625 354 (February 21st 2014)

bull Fixed Placeholder functionality (including tests)

bull Fixed Convertnormalize filenames (including tests)

bull Fixed Handling uppercase extensions with browse

626 353 (January 7 2014)

bull New added path_full to FileObject

bull Improved added docx to EXTENSIONS

bull Improved Recommend pillow instead of PIL as a requirement

bull Improved Added additional test cases

bull Improved Updated documentation

bull Improved Consistent use of storage (eg storagelocation storageurl)

bull Improved Removed unnecessary functions (eg url_join url_strip)

bull Improved Moved sort_by_attr to FileListing

bull Improved Regex matches with file versions on browse

bull Improved Using djangoconfurls (with djangoconfurlsdefaults as fallback)

bull Improved Adding CONTRIBUTINGrst

bull Improved Removed static Media inner class with fields

bull Improved Removed search icon with fields (has not being used)

bull Improved Added custom class attributes with filebrowser field

bull Improved Updated translations

bull Fixed fixed exception handling with python 25

bull Fixed fixes dir with SEARCH_TRAVERSE true and version select

bull Fixed Make Django FileUploadHandlers work (also fixed a memory leak)

bull Fixed return correct filename with OVERWRITE_EXISTING

bull Fixed fb_version_generate with FILEBROWSER_VERSIONS_BASEDIR

bull Fixed Table sorting with ascdesc

bull Fixed Added DeprecationWarning for FileObjectdirectory and FileObjectfolder

36 Chapter 6 Help

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

Django FileBrowser Documentation Release 357

gtgtgt for item in filelistingfiles_walk_filtered() print itemuploadsbloguploadsblog1uploadsblog1imagesuploadsblog1imagesblogimagejpguploadstestfolderuploadstestfoldertestimagejpg

Note The versions are not listed (compared with files_walk_total) because of filter_func

results_listing_total()Number of total files based on files_listing_total()

gtgtgt filelistingresults_listing_total()2

results_walk_total()Number of total files based on files_walk_total()

gtgtgt filelistingresults_walk_total()10

results_listing_filtered()Number of filtered files based on files_listing_filtered()

gtgtgt filelistingresults_listing_filtered()2

results_walk_filtered()Number of filtered files based on files_walk_filtered()

gtgtgt filelistingresults_walk_filtered()6

212 FileObject

class FileObject(path site=None)An object representing a media file

Parameters

bull path ndash Relative path to a location within sitestoragelocation

bull site ndash An optional FileBrowser Site

For example

from filebrowsersites import sitefrom filebrowserbase import FileObjectfileobject = FileObject(ospathjoin(sitedirectorytestfoldertestimagejpg))version = FileObject(ospathjoin(fileobjectversions_basedir testfolder testimage_mediumjpg))

21 API 13

Django FileBrowser Documentation Release 357

Attributes

Initial Attributes

pathPath relative to a storage location (including sitedirectory)

gtgtgt fileobjectpathuploadstestfoldertestimagejpg

headThe directory name of pathname path

gtgtgt fileobjectheaduploadstestfolder

filenameName of the file (including the extension) or name of the folder

gtgtgt fileobjectfilenametestimagejpg

filename_lowerLower type of filename

filename_rootFilename without extension

gtgtgt fileobjectfilename_roottestimage

extensionFile extension including the dot With a folder the extensions is None

gtgtgt fileobjectextensionjpg

mimetypeMimetype based on httpdocspythonorglibrarymimetypeshtml

gtgtgt fileobjectmimetype(imagejpeg None)

General Attributes

filetypeType of the file as defined with EXTENSIONS

gtgtgt fileobjectfiletypeImage

filesizeFilesize in Bytes

gtgtgt fileobjectfilesize870037L

14 Chapter 2 API

Django FileBrowser Documentation Release 357

dateDate based on timemktime

gtgtgt fileobjectdate12997603470

datetimeDatetime object

gtgtgt fileobjectdatetimedatetimedatetime(2011 3 10 13 32 27)

existsTrue if the path exists False otherwise

gtgtgt fileobjectexistsTrue

Path and URL attributes

pathPath relative to a storage location (including sitedirectory)

gtgtgt fileobjectpathuploadstestfoldertestimagejpg

path_relative_directoryPath relative to sitedirectory

gtgtgt fileobjectpath_relative_directorytestfoldertestimagejpg

path_fullAbsolute server path (based on storagepath)

gtgtgt fileobjectpath_fullabsolutepathtoserverlocationtestfoldertestimagejpg

dirnameNew in version 34

The directory (not including sitedirectory)

gtgtgt fileobjectdirnametestfolder

urlURL for the filefolder (based on storageurl)

gtgtgt fileobjecturlmediauploadstestfoldertestimagejpg

Image attributes

The image attributes are only useful if the FileObject represents an image

dimensionsImage dimensions as a tuple

21 API 15

Django FileBrowser Documentation Release 357

gtgtgt fileobjectdimensions(1000 750)

widthImage width in px

gtgtgt fileobjectwidth1000

heightImage height in px

gtgtgt fileobjectheight750

aspectratioAspect ratio (float format)

gtgtgt fileobjectaspectratio133534908

orientationImage orientation either Landscape or Portrait

gtgtgt fileobjectorientationLandscape

Folder attributes

The folder attributes make sense when the FileObject represents a directory (not a file)

directory

Deprecated since version 353 Use path_relative_directory instead

folder

Deprecated since version 353 Use dirname instead

is_folderTrue if path is a folder

gtgtgt fileobjectis_folderFalse

is_emptyTrue if the folder is empty False if the folder is not empty or the FileObject is not a folder

gtgtgt fileobjectis_emptyFalse

Version attributes

is_versiontrue if the File is a version of another File

16 Chapter 2 API

Django FileBrowser Documentation Release 357

gtgtgt fileobjectis_versionFalsegtgtgt versionis_versionTrue

versions_basedirThe relative path (from storage location) to the main versions folder Either VERSIONS_BASEDIR orsitedirectory

gtgtgt fileobjectversions_basedir_versionsgtgtgt versionversions_basedir_versions

originalReturns the original FileObject

gtgtgt fileobjectoriginalltFileObject uploadstestfoldertestimagejpggtgtgtgt versionoriginalltFileObject uploadstestfoldertestimagejpggt

original_filenameGet the filename of an original image from a version

gtgtgt fileobjectoriginal_filenametestimagejpggtgtgt versionoriginal_filenametestimagejpg

Methods

Version methods

versions()List all filenames based on VERSIONS

gtgtgt fileobjectversions()[_versionstestfoldertestimage_admin_thumbnailjpg_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionversions()[]

Note The versions are not being generated

admin_versions()List all filenames based on ADMIN_VERSIONS

gtgtgt fileobjectadmin_versions()[_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg

21 API 17

Django FileBrowser Documentation Release 357

_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionadmin_versions()[]

Note The versions are not being generated

version_name(version_suffix)Get the filename for a version

gtgtgt fileobjectversion_name(medium)testimage_mediumjpg

Note The version is not being generated

version_path(version_suffix)Get the path for a version

gtgtgt fileobjectversion_path(medium)_versionstestfoldertestimage_mediumjpg

Note The version is not being generated

version_generate(version_suffix)Generate a version

gtgtgt fileobjectversion_generate(medium)ltFileObject uploadstestfoldertestimage_mediumjpggt

Please note that a version is only generated if it does not already exist or if the original image is newer than theexisting version

Delete methods

delete()Delete the File or Folder from the server

Warning If you delete a Folder all items within the folder are being deleted

delete_versions()Delete all VERSIONS

delete_admin_versions()Delete all ADMIN_VERSIONS

18 Chapter 2 API

CHAPTER 3

Fields amp Widgets

31 Fields amp Widgets

The FileBrowseField is a custom model field which returns a FileObject The widgets FileInput and ClearableFileIn-put are used with the admin app in order to show an additional thumbnail for images

311 FileBrowseField

class FileBrowseField(max_length[ site directory extensions format options])A subclass of CharField referencing a media file within Returns a FileObject

Parameters

bull site ndash A FileBrowser site (defaults to the main site) see FileBrowser Site

bull directory ndash Directory to browse when clicking the search icon

bull extensions ndash List of allowed extensions see Extensions and Formats

bull format ndash A key from SELECT_FORMATS in order to restrict the selection to specificfiletypes see Extensions and Formats

For example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 directory=images extensions=[jpg] blank=True null=True)document = FileBrowseField(PDF max_length=200 directory=documents extensions=[pdfdoc] blank=True null=True)

FileBrowseField in Templates

You can use all attributes from FileObject

blogentryimage ltimg src= publicationimageurl gt

ifequal blogentryimageimage_orientation landscape ltimg src= blogentryimageurl class=landscape gt

endifequal

19

Django FileBrowser Documentation Release 357

Showing Thumbnail in the Changelist

To show a thumbnail with the changelist you can define a ModelAdmin method

from filebrowsersettings import ADMIN_THUMBNAIL

def image_thumbnail(self obj)if objimage and objimagefiletype == Image

return ltimg src=s gt objimageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Using the FileBrowseField with TinyMCE

In order to replace the TinyMCE imagefile manager with the FileBrowser you have to use a FileBrowser CallbackTherersquos an example TinyMCE configuration file in staticjs called TinyMCEAdminjs You can either copy theFileBrowserCallback to your own file or just use tinymce_setupjs (which comes with django-grappelli)

Just add these lines to your ModelAdmin asset definitions

class Mediajs = [pathtotinymcejscriptstiny_mcetiny_mcejs

pathtoyourtinymce_setupjs]

312 FileInput

Subclass of FileInput with an additional thumbnail

from filebrowserwidgets import FileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget FileInput

313 ClearableFileInput

Subclass of ClearableFileInput with an additional thumbnail

from filebrowserwidgets import ClearableFileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget ClearableFileInput

314 Django FileField and the FileBrowser

Return a FileObject from a FileField or ImageField with

20 Chapter 3 Fields amp Widgets

Django FileBrowser Documentation Release 357

from filebrowserbase import FileObject

image_upload = modelsImageField(uImage (Upload) max_length=250 upload_to=image_upload_path blank=True null=True)

def image(self)if selfimage_upload

return FileObject(selfimage_uploadpath)return None

In order show a thumbnail with your changelist you could use a ModelAdmin method

from filebrowserbase import FileObject

def image_thumbnail(self obj)if objimage_upload

image = FileObject(objimage_uploadpath)if imagefiletype == Image

return ltimg src=s gt imageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Note There are different ways to achieve this The above examples show one of several options

31 Fields amp Widgets 21

Django FileBrowser Documentation Release 357

22 Chapter 3 Fields amp Widgets

CHAPTER 4

Admin Interface

41 Admin Interface

The main FileBrowser admin application is an extension for the Django admin interface in order to browser yourmedia folder upload and renamedelete files

411 FileBrowser Site

New in version 340

class FileBrowserSite(name=None app_name=rsquofilebrowserrsquo storage=default_storage)Respresents the FileBrowser admin application (similar to Djangorsquos admin site)

Parameters

bull name ndash A name for the site defaults to None

bull app_name ndash Defaults to lsquofilebrowserrsquo

bull storage ndash A custom storage engine defaults to Djangos default storage

Similar to djangocontribadmin you first need to add a filebrowsersite to your admin interface Inyour urlspy import the default FileBrowser site (or your custom site) and add the site to your URL-patterns (beforeany admin-urls)

from filebrowsersites import site

urlpatterns = patterns(url(r^adminurlfilebrowser include(siteurls))

)

Now you are able to browse the location defined with the storage engine associated to your site

from djangocorefilesstorage import DefaultStoragefrom filebrowsersites import FileBrowserSite

Default FileBrowser sitesite = FileBrowserSite(name=filebrowser storage=DefaultStorage())

My Custom FileBrowser sitecustom_site = FileBrowserSite(name=custom_filebrowser storage=DefaultStorage())custom_sitedirectory = custom_uploads

23

Django FileBrowser Documentation Release 357

Note The module variable site from filebrowsersites is the default FileBrowser application

412 Custom Actions

New in version 340

Similar to Djangorsquos admin actions you can define your FileBrowser actions and thus automate the typical tasks ofyour users Registered custom actions are listed in the detail view of a file and a user can select a single action at atime The selected action will then be applied to the file

The default FileBrowser image actions such as ldquoFlip Verticalrdquo or ldquoRotate 90deg Clockwiserdquo are in fact implemented ascustom actions (see the module filebrowseractions)

Writing Your Own Actions

Custom actions are simple functions

def foo(request fileobjects) Do something with the fileobjects

The first parameter is a HttpRequest object (representing the submitted form in which a user selected the action)and the second parameter is a list of FileObjects to which the action should be applied

The list contains exactly one instance of FileObject (representing the file from the detail view) but this may change inthe future as custom actions may become available also in browse views (similar to admin actions applied to a list ofchecked objects)

Registering an Action

In order to make your action visible you need to register it with a FileBrowser site

siteadd_action(foo)

Once registered the action will appear in the detail view of a file You can also give your action a short description

fooshort_description = Do foo with the File

This short description will then appear in the list of available actions If you do not provide a short description thefunction name will be used instead and FileBrowser will replace any underscores in the function name with spaces

Associating Actions with Specific Files

Each custom action can be associated with a specific file type (eg images audio file etc) to which it applies In orderto do that you need to define a predicatefilter function which takes a single argument (FileObject) and returns Trueif your action is applicable to that FileObject Finally you need to register this filter function with your action

fooapplies_to(lambda fileobject fileobjectfiletype == Image)

In the above example foo will appear in the action list only for image files If you do not specify any filter functionfor your action FileBrowser considers the action as applicable to all files

24 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

Messages amp Intermediate Pages

You can provide a feedback to a user about a successful or failed execution of an action by using a message Forexample

from djangocontrib import messages

def desaturate_image(request fileobjects)for f in fileobjects

Desaturate the imagemessagesadd_message(request messagesSUCCESS _(Image s was desaturated) ffilename)

Some actions may require user confirmation (eg in order to prevent accidental and irreversible modification tofiles) In order to that follow the same pattern as with Djangorsquos admin action and return a HttpResponse objectfrom your action Good practice for intermediate pages is to implement a confirm view and have your action returnHttpResponseRedirect

def crop_image(request fileobjects)files = ampf=join([fpath_relative for f in fileobjects])return HttpResponseRedirect(confirmaction=crop_imageampf=s files)

413 File Storages

New in version 340

You have the option to specify which file storage engine a FileBrowser should use to browseuploadmodify yourmedia files This enables you to use a FileBrowser even if your media files are located at some remote system Seealso the Djangorsquos documentation on storages httpsdocsdjangoprojectcomendevtopicsfiles

To associate a FileBrowser site with a particular storage engine set the storage property of a site object

from djangocorefilesstorage import FileSystemStoragesitestorage = FileSystemStorage(location=pathtomediadirectory base_url=media)

For storage classes other than FileSystemStorage (or those that inherit from that class) therersquos more effort involved inproviding a storage object that can be used with FileBrowser See StorageMixin Class

Note Prior FileBrowser 34 the way to specify FileBrowserlsquos MEDIA_ROOT and MEDIA_URL was via settingspyStarting from version 34 those variables are associated with the storage instance and you can set them as illustratedin the above example

Warning For the reason of backward compatibility FileBrowser settings FILEBROWSER_MEDIA_ROOT andFILEBROWSER_MEDIA_URL can still be used to customize FileBrowser as long as yoursquore using the defaultFileBrowserlsquos site without having changed its storage engine In the next major release of FileBrowser thesesettings will be removed

StorageMixin Class

A FileBrowser uses the Djangorsquos Storage class to access media files However the API of the Storageclass does not provide all methods necessary for FileBrowserrsquos functionality A StorageMixin class fromfilebrowserstorage module therefore defines all the additional methods that a FileBrowser requires

isdir(self name)Returns true if name exists and is a directory

41 Admin Interface 25

Django FileBrowser Documentation Release 357

isfile(self name)Returns true if name exists and is a regular file

move(self old_file_name new_file_name allow_overwrite=False)Moves safely a file from one location to another If allow_ovewrite==False and new_file_nameexists raises an exception

makedirs(self name)Creates all missing directories specified by name Analogue to osmkdirs()

414 Views

All views use the staff_member_requird and path_exists decorator in order to check if the server pathactually exists Some views also use the file_exists decorator

bull Browse fb_browse Browse a directory on your server Returns a FileListing

ndash Optional query string args dir o ot q p filter_date filter_type type

bull Create directory fb_createdir Create a new folder on your server

ndash Optional query string args dir

ndash Signals filebrowser_pre_createdir filebrowser_post_createdir

bull Upload fb_upload Multiple upload

ndash Optional query string args dir type

ndash Signals filebrowser_pre_upload filebrowser_post_upload

bull Edit fb_edit Edit a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_rename filebrowser_post_rename

You are able to apply custom actions (see Custom Actions) to the edit-view

bull Confirm delete fb_confirm_delete Confirm the deletion of a file or folder

ndash Required query string args filename

ndash Optional query string args dir

If you try to delete a folder all filesfolders within this folder are listed on this page

bull Delete fb_delete Delete a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_delete filebrowser_post_delete

Warning If you delete a Folder all items within this Folder are being deleted

bull Version fb_version Generate a version of an image as defined with ADMIN_VERSIONS

ndash Required query string args filename

ndash Optional Query string args dir

This is a helper used by the FileBrowseField and TinyMCE for selecting a version

26 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

415 Signals

The FileBrowser sends a couple of different signals Please take a look at the module filebrowsersignals for furtherexplanation on the provided arguments

bull filebrowser_pre_upload Sent before a an Upload starts

bull filebrowser_post_upload Sent after an Upload has finished

bull filebrowser_pre_delete Sent before an Item (File Folder) is deleted

bull filebrowser_post_delete Sent after an Item (File Folder) has been deleted

bull filebrowser_pre_createdir Sent before a new Folder is created

bull filebrowser_post_createdir Sent after a new Folder has been created

bull filebrowser_pre_rename Sent before an Item (File Folder) is renamed

bull filebrowser_post_rename Sent after an Item (File Folder) has been renamed

bull filebrowser_actions_pre_apply Sent before a custom action is applied

bull filebrowser_actions_post_apply Sent after a custom action has been applied

Example for using these Signals

Herersquos a small example for using the above Signals

from filebrowser import signals

def pre_upload_callback(sender kwargs)Receiver function called before an upload startsprint Pre Upload Callbackprint kwargs kwargs

signalsfilebrowser_pre_uploadconnect(pre_upload_callback)

def post_upload_callback(sender kwargs)Receiver function called each time an upload has finishedprint Post Upload Callbackprint kwargs kwargs You can use all attributes available with the FileObject This is just an example print Filesize kwargs[file]filesizeprint Orientation kwargs[file]orientationprint Extension kwargs[file]extension

signalsfilebrowser_post_uploadconnect(post_upload_callback)

41 Admin Interface 27

Django FileBrowser Documentation Release 357

28 Chapter 4 Admin Interface

CHAPTER 5

Image Versions

51 Versions

With the FileBrowser you are able to define different versionssizes for images This enables you to save an originalimage on your server while having different versions of that image to automatically fit your websites grid Versionsare also useful for responsiveadaptive layouts

511 Defining Versions

New in version 340 methods

First you need to know which versionssizes of an image yoursquod like to generate with your website Letrsquos say yoursquoreusing a 12 column grid with 60px for each column and 20px margin (which is a total of 940px) With this grid youcould (for example) define these image versions

FILEBROWSER_VERSIONS_BASEDIR = _versionsFILEBROWSER_VERSIONS =

admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

Use the methods argument if you need to add a filter

def grayscale(im)Convert image to grayscaleif immode = L

im = imconvert(L)return im

FILEBROWSER_VERSIONS = big verbose_name Big (6 col) width 460 height opts methods [grayscale]

)

29

Django FileBrowser Documentation Release 357

512 Versions and the Admin

When using the FileBrowser with the admin interface you need to define ADMIN_VERSIONS andADMIN_THUMBNAIL (see Settings) ADMIN_VERSIONS are available with the admin ie you are able to seethese versions with the image detail view and you are able to select the versions with the FileBrowseField model field

FILEBROWSER_ADMIN_VERSIONS = [thumbnail small medium big large]FILEBROWSER_ADMIN_THUMBNAIL = admin_thumbnail

513 Versions and the Frontend

With your templates you have two different tags to choose from version and version_object With bothtags the version will be generated if it doesnrsquot already exist OR if the original image is newer than the version Inorder to update an image you just overwrite the original image and the versions will be generated automatically (asyou request them within your template)

A Model example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 blank=True null=True)

With your templates use version if you simply need to retrieve the URL or version_object if you need to geta FileObject

lt-- load filebrowser templatetags --gt load fb_versions

lt-- get the url with version --gtltimg src= version blogentryimage medium gt

lt-- get a fileobject with version_object --gt version_object blogentryimage medium as version_medium version_mediumwidth ltimg src= version_medium gt

Templatetag version

RetrievesGenerates a version and returns an URL

version modelfield_name version_prefix

Templatetag version_object

RetrievesGenerates a version and returns a FileObject

version_object modelfield_name version_prefix as variable

Note With both templatetags version_prefix can either be a string or a variable If version_prefix is astring use quotes

30 Chapter 5 Image Versions

Django FileBrowser Documentation Release 357

514 Versions in Views

If you have a FileObject you can generateretrieve a version with

v = objimageversion_generate(version_prefix) returns a FileObject

515 Placeholder

When developing on a locale machine or a development-server you might not have all the images (resp media-files)available that are on your production instance and downloading these files on a regular basis might not be an option

In that case you can use a placeholder instead of a version You just need to define the PLACEHOLDER and overwritethe settings SHOW_PLACEHOLDER andor FORCE_PLACEHOLDER (see Placeholder)

516 Management Commands

fb_version_generateIf you need to generate certain (or all) versions type

python managepy fb_version_generate

fb_version_removeIf you need to generate certain (or all) versions type

python managepy fb_version_generate

Warning Please be very careful with this command

51 Versions 31

Django FileBrowser Documentation Release 357

32 Chapter 5 Image Versions

CHAPTER 6

Help

61 Help

611 FAQ

Why should I use the FileBrowser

If you need your editors or customers to manage files the FileBrowser is an alternative to an FTP-client Moreoveryou are able to define different image versions according to your websites grid Alternatives to the FileBrowser can befound at httpdjangopackagescomgridsgfile-managers

Do I need Grappelli

Grappelli is a requirement for using the FileBrowser There are several filebrowser-no-grappelli repositories (most ofthem on GitHub) but we donrsquot follow the development

I need help

see Troubleshooting

Why are there no fancy effects

The FileBrowser is about managing files We think that you should prepare your files before uploading them to theserver

How do I upload to another server

Use a custom storage engine see httpsdocsdjangoprojectcomen16howtocustom-file-storage

Why do I need image-versions

You need image-versions if your website is based on a grid

33

Django FileBrowser Documentation Release 357

Is the FileBrowser stable

Wersquove developed the FileBrowser for a couple of years and use it with almost all of our clients That said Grappelli isthe more stable and mature application

How can I contribute

Help is very much needed and appreciated Test the FileBrowser and submit feedbackpatches

Who develops the FileBrowser

The FileBrowser is developed and maintained by Patrick Kranzlmuumlller amp Axel Swoboda of vonautomatisch

612 Troubleshooting

Check your setup

Please check if the problem is caused by your setup

bull Read Quick start guide

bull Check if the staticmedia-files are served correctly

bull Make sure you have removed all custom FileBrowser templates from all locations in TEMPLATE_DIRS orcheck that these templates are compatible with the FileBrowser

Run the tests

Start the shell and type

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Check issues

If your setup is fine please check if your problem is a known issue

bull Take a look at all FileBrowser Issues (incuding closed) and search the FileBrowser Google-Group

Add a ticket

If you think yoursquove found a bug please add a ticket

bull Try to describe your problem as precisely as possible

bull Tell us what you did in order to solve the problem

bull Tell us what version of the FileBrowser you are using

bull Tell us what version of Django you are using

34 Chapter 6 Help

Django FileBrowser Documentation Release 357

bull Please do NOT add tickets if yoursquore having problems with serving staticmedia-files (because this is not relatedto the FileBrowser)

bull Please do NOT add tickets referring to Djangos trunk version

bull At best add a patch

Note Be aware that we may close issues not following these guidlines without further notifications

613 Translation

Translation is done via Transifex

Supported Languages

see httpswwwtransifexnetprojectspdjango-filebrowserresourcedjangopo

614 FileBrowser 35 Release Notes

FileBrowser 35 is compatible with Django 14151617 as well as Grappelli 242526

Update from FileBrowser 34x

bull Update Django to 14151617 and check httpsdocsdjangoprojectcomendevreleases14 orhttpsdocsdjangoprojectcomendevreleases15 or httpsdocsdjangoprojectcomendevreleases16

bull Update Grappelli to 24x25x26x

bull Update FileBrowser to 35x

62 Changelog

621 358 (not yet released)

622 357 (September 10th 2014)

bull New Compatibility with Django 17 and Grappelli 26x

bull Improved Updated tests because of the new random suffix with get_available_name (django storage)

bull Improved Added an icon in order to mark finished uploads

bull Improved Show resulting filename (eg with suffix converted) after successful upload

bull Fixed Permissions with file upload

bull Fixed Unified json response with _upload_file (no matter if file already exists or not)

623 356 (April 16th 2014)

bull Fixed Displaying pagination correctly with lots of entries

62 Changelog 35

Django FileBrowser Documentation Release 357

624 355 (April 13th 2014)

bull New Added client-side (JavaScript) file extension validation to the AJAX uploader

bull New Added experimental Python 33 support

bull Improved Tests with convertnormalize (removed special chars from test filename)

bull Fixed File selection after using search box (CKEditor)

bull Fixed Removed encoding of file URIs with CKEditor

625 354 (February 21st 2014)

bull Fixed Placeholder functionality (including tests)

bull Fixed Convertnormalize filenames (including tests)

bull Fixed Handling uppercase extensions with browse

626 353 (January 7 2014)

bull New added path_full to FileObject

bull Improved added docx to EXTENSIONS

bull Improved Recommend pillow instead of PIL as a requirement

bull Improved Added additional test cases

bull Improved Updated documentation

bull Improved Consistent use of storage (eg storagelocation storageurl)

bull Improved Removed unnecessary functions (eg url_join url_strip)

bull Improved Moved sort_by_attr to FileListing

bull Improved Regex matches with file versions on browse

bull Improved Using djangoconfurls (with djangoconfurlsdefaults as fallback)

bull Improved Adding CONTRIBUTINGrst

bull Improved Removed static Media inner class with fields

bull Improved Removed search icon with fields (has not being used)

bull Improved Added custom class attributes with filebrowser field

bull Improved Updated translations

bull Fixed fixed exception handling with python 25

bull Fixed fixes dir with SEARCH_TRAVERSE true and version select

bull Fixed Make Django FileUploadHandlers work (also fixed a memory leak)

bull Fixed return correct filename with OVERWRITE_EXISTING

bull Fixed fb_version_generate with FILEBROWSER_VERSIONS_BASEDIR

bull Fixed Table sorting with ascdesc

bull Fixed Added DeprecationWarning for FileObjectdirectory and FileObjectfolder

36 Chapter 6 Help

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

Django FileBrowser Documentation Release 357

Attributes

Initial Attributes

pathPath relative to a storage location (including sitedirectory)

gtgtgt fileobjectpathuploadstestfoldertestimagejpg

headThe directory name of pathname path

gtgtgt fileobjectheaduploadstestfolder

filenameName of the file (including the extension) or name of the folder

gtgtgt fileobjectfilenametestimagejpg

filename_lowerLower type of filename

filename_rootFilename without extension

gtgtgt fileobjectfilename_roottestimage

extensionFile extension including the dot With a folder the extensions is None

gtgtgt fileobjectextensionjpg

mimetypeMimetype based on httpdocspythonorglibrarymimetypeshtml

gtgtgt fileobjectmimetype(imagejpeg None)

General Attributes

filetypeType of the file as defined with EXTENSIONS

gtgtgt fileobjectfiletypeImage

filesizeFilesize in Bytes

gtgtgt fileobjectfilesize870037L

14 Chapter 2 API

Django FileBrowser Documentation Release 357

dateDate based on timemktime

gtgtgt fileobjectdate12997603470

datetimeDatetime object

gtgtgt fileobjectdatetimedatetimedatetime(2011 3 10 13 32 27)

existsTrue if the path exists False otherwise

gtgtgt fileobjectexistsTrue

Path and URL attributes

pathPath relative to a storage location (including sitedirectory)

gtgtgt fileobjectpathuploadstestfoldertestimagejpg

path_relative_directoryPath relative to sitedirectory

gtgtgt fileobjectpath_relative_directorytestfoldertestimagejpg

path_fullAbsolute server path (based on storagepath)

gtgtgt fileobjectpath_fullabsolutepathtoserverlocationtestfoldertestimagejpg

dirnameNew in version 34

The directory (not including sitedirectory)

gtgtgt fileobjectdirnametestfolder

urlURL for the filefolder (based on storageurl)

gtgtgt fileobjecturlmediauploadstestfoldertestimagejpg

Image attributes

The image attributes are only useful if the FileObject represents an image

dimensionsImage dimensions as a tuple

21 API 15

Django FileBrowser Documentation Release 357

gtgtgt fileobjectdimensions(1000 750)

widthImage width in px

gtgtgt fileobjectwidth1000

heightImage height in px

gtgtgt fileobjectheight750

aspectratioAspect ratio (float format)

gtgtgt fileobjectaspectratio133534908

orientationImage orientation either Landscape or Portrait

gtgtgt fileobjectorientationLandscape

Folder attributes

The folder attributes make sense when the FileObject represents a directory (not a file)

directory

Deprecated since version 353 Use path_relative_directory instead

folder

Deprecated since version 353 Use dirname instead

is_folderTrue if path is a folder

gtgtgt fileobjectis_folderFalse

is_emptyTrue if the folder is empty False if the folder is not empty or the FileObject is not a folder

gtgtgt fileobjectis_emptyFalse

Version attributes

is_versiontrue if the File is a version of another File

16 Chapter 2 API

Django FileBrowser Documentation Release 357

gtgtgt fileobjectis_versionFalsegtgtgt versionis_versionTrue

versions_basedirThe relative path (from storage location) to the main versions folder Either VERSIONS_BASEDIR orsitedirectory

gtgtgt fileobjectversions_basedir_versionsgtgtgt versionversions_basedir_versions

originalReturns the original FileObject

gtgtgt fileobjectoriginalltFileObject uploadstestfoldertestimagejpggtgtgtgt versionoriginalltFileObject uploadstestfoldertestimagejpggt

original_filenameGet the filename of an original image from a version

gtgtgt fileobjectoriginal_filenametestimagejpggtgtgt versionoriginal_filenametestimagejpg

Methods

Version methods

versions()List all filenames based on VERSIONS

gtgtgt fileobjectversions()[_versionstestfoldertestimage_admin_thumbnailjpg_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionversions()[]

Note The versions are not being generated

admin_versions()List all filenames based on ADMIN_VERSIONS

gtgtgt fileobjectadmin_versions()[_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg

21 API 17

Django FileBrowser Documentation Release 357

_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionadmin_versions()[]

Note The versions are not being generated

version_name(version_suffix)Get the filename for a version

gtgtgt fileobjectversion_name(medium)testimage_mediumjpg

Note The version is not being generated

version_path(version_suffix)Get the path for a version

gtgtgt fileobjectversion_path(medium)_versionstestfoldertestimage_mediumjpg

Note The version is not being generated

version_generate(version_suffix)Generate a version

gtgtgt fileobjectversion_generate(medium)ltFileObject uploadstestfoldertestimage_mediumjpggt

Please note that a version is only generated if it does not already exist or if the original image is newer than theexisting version

Delete methods

delete()Delete the File or Folder from the server

Warning If you delete a Folder all items within the folder are being deleted

delete_versions()Delete all VERSIONS

delete_admin_versions()Delete all ADMIN_VERSIONS

18 Chapter 2 API

CHAPTER 3

Fields amp Widgets

31 Fields amp Widgets

The FileBrowseField is a custom model field which returns a FileObject The widgets FileInput and ClearableFileIn-put are used with the admin app in order to show an additional thumbnail for images

311 FileBrowseField

class FileBrowseField(max_length[ site directory extensions format options])A subclass of CharField referencing a media file within Returns a FileObject

Parameters

bull site ndash A FileBrowser site (defaults to the main site) see FileBrowser Site

bull directory ndash Directory to browse when clicking the search icon

bull extensions ndash List of allowed extensions see Extensions and Formats

bull format ndash A key from SELECT_FORMATS in order to restrict the selection to specificfiletypes see Extensions and Formats

For example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 directory=images extensions=[jpg] blank=True null=True)document = FileBrowseField(PDF max_length=200 directory=documents extensions=[pdfdoc] blank=True null=True)

FileBrowseField in Templates

You can use all attributes from FileObject

blogentryimage ltimg src= publicationimageurl gt

ifequal blogentryimageimage_orientation landscape ltimg src= blogentryimageurl class=landscape gt

endifequal

19

Django FileBrowser Documentation Release 357

Showing Thumbnail in the Changelist

To show a thumbnail with the changelist you can define a ModelAdmin method

from filebrowsersettings import ADMIN_THUMBNAIL

def image_thumbnail(self obj)if objimage and objimagefiletype == Image

return ltimg src=s gt objimageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Using the FileBrowseField with TinyMCE

In order to replace the TinyMCE imagefile manager with the FileBrowser you have to use a FileBrowser CallbackTherersquos an example TinyMCE configuration file in staticjs called TinyMCEAdminjs You can either copy theFileBrowserCallback to your own file or just use tinymce_setupjs (which comes with django-grappelli)

Just add these lines to your ModelAdmin asset definitions

class Mediajs = [pathtotinymcejscriptstiny_mcetiny_mcejs

pathtoyourtinymce_setupjs]

312 FileInput

Subclass of FileInput with an additional thumbnail

from filebrowserwidgets import FileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget FileInput

313 ClearableFileInput

Subclass of ClearableFileInput with an additional thumbnail

from filebrowserwidgets import ClearableFileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget ClearableFileInput

314 Django FileField and the FileBrowser

Return a FileObject from a FileField or ImageField with

20 Chapter 3 Fields amp Widgets

Django FileBrowser Documentation Release 357

from filebrowserbase import FileObject

image_upload = modelsImageField(uImage (Upload) max_length=250 upload_to=image_upload_path blank=True null=True)

def image(self)if selfimage_upload

return FileObject(selfimage_uploadpath)return None

In order show a thumbnail with your changelist you could use a ModelAdmin method

from filebrowserbase import FileObject

def image_thumbnail(self obj)if objimage_upload

image = FileObject(objimage_uploadpath)if imagefiletype == Image

return ltimg src=s gt imageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Note There are different ways to achieve this The above examples show one of several options

31 Fields amp Widgets 21

Django FileBrowser Documentation Release 357

22 Chapter 3 Fields amp Widgets

CHAPTER 4

Admin Interface

41 Admin Interface

The main FileBrowser admin application is an extension for the Django admin interface in order to browser yourmedia folder upload and renamedelete files

411 FileBrowser Site

New in version 340

class FileBrowserSite(name=None app_name=rsquofilebrowserrsquo storage=default_storage)Respresents the FileBrowser admin application (similar to Djangorsquos admin site)

Parameters

bull name ndash A name for the site defaults to None

bull app_name ndash Defaults to lsquofilebrowserrsquo

bull storage ndash A custom storage engine defaults to Djangos default storage

Similar to djangocontribadmin you first need to add a filebrowsersite to your admin interface Inyour urlspy import the default FileBrowser site (or your custom site) and add the site to your URL-patterns (beforeany admin-urls)

from filebrowsersites import site

urlpatterns = patterns(url(r^adminurlfilebrowser include(siteurls))

)

Now you are able to browse the location defined with the storage engine associated to your site

from djangocorefilesstorage import DefaultStoragefrom filebrowsersites import FileBrowserSite

Default FileBrowser sitesite = FileBrowserSite(name=filebrowser storage=DefaultStorage())

My Custom FileBrowser sitecustom_site = FileBrowserSite(name=custom_filebrowser storage=DefaultStorage())custom_sitedirectory = custom_uploads

23

Django FileBrowser Documentation Release 357

Note The module variable site from filebrowsersites is the default FileBrowser application

412 Custom Actions

New in version 340

Similar to Djangorsquos admin actions you can define your FileBrowser actions and thus automate the typical tasks ofyour users Registered custom actions are listed in the detail view of a file and a user can select a single action at atime The selected action will then be applied to the file

The default FileBrowser image actions such as ldquoFlip Verticalrdquo or ldquoRotate 90deg Clockwiserdquo are in fact implemented ascustom actions (see the module filebrowseractions)

Writing Your Own Actions

Custom actions are simple functions

def foo(request fileobjects) Do something with the fileobjects

The first parameter is a HttpRequest object (representing the submitted form in which a user selected the action)and the second parameter is a list of FileObjects to which the action should be applied

The list contains exactly one instance of FileObject (representing the file from the detail view) but this may change inthe future as custom actions may become available also in browse views (similar to admin actions applied to a list ofchecked objects)

Registering an Action

In order to make your action visible you need to register it with a FileBrowser site

siteadd_action(foo)

Once registered the action will appear in the detail view of a file You can also give your action a short description

fooshort_description = Do foo with the File

This short description will then appear in the list of available actions If you do not provide a short description thefunction name will be used instead and FileBrowser will replace any underscores in the function name with spaces

Associating Actions with Specific Files

Each custom action can be associated with a specific file type (eg images audio file etc) to which it applies In orderto do that you need to define a predicatefilter function which takes a single argument (FileObject) and returns Trueif your action is applicable to that FileObject Finally you need to register this filter function with your action

fooapplies_to(lambda fileobject fileobjectfiletype == Image)

In the above example foo will appear in the action list only for image files If you do not specify any filter functionfor your action FileBrowser considers the action as applicable to all files

24 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

Messages amp Intermediate Pages

You can provide a feedback to a user about a successful or failed execution of an action by using a message Forexample

from djangocontrib import messages

def desaturate_image(request fileobjects)for f in fileobjects

Desaturate the imagemessagesadd_message(request messagesSUCCESS _(Image s was desaturated) ffilename)

Some actions may require user confirmation (eg in order to prevent accidental and irreversible modification tofiles) In order to that follow the same pattern as with Djangorsquos admin action and return a HttpResponse objectfrom your action Good practice for intermediate pages is to implement a confirm view and have your action returnHttpResponseRedirect

def crop_image(request fileobjects)files = ampf=join([fpath_relative for f in fileobjects])return HttpResponseRedirect(confirmaction=crop_imageampf=s files)

413 File Storages

New in version 340

You have the option to specify which file storage engine a FileBrowser should use to browseuploadmodify yourmedia files This enables you to use a FileBrowser even if your media files are located at some remote system Seealso the Djangorsquos documentation on storages httpsdocsdjangoprojectcomendevtopicsfiles

To associate a FileBrowser site with a particular storage engine set the storage property of a site object

from djangocorefilesstorage import FileSystemStoragesitestorage = FileSystemStorage(location=pathtomediadirectory base_url=media)

For storage classes other than FileSystemStorage (or those that inherit from that class) therersquos more effort involved inproviding a storage object that can be used with FileBrowser See StorageMixin Class

Note Prior FileBrowser 34 the way to specify FileBrowserlsquos MEDIA_ROOT and MEDIA_URL was via settingspyStarting from version 34 those variables are associated with the storage instance and you can set them as illustratedin the above example

Warning For the reason of backward compatibility FileBrowser settings FILEBROWSER_MEDIA_ROOT andFILEBROWSER_MEDIA_URL can still be used to customize FileBrowser as long as yoursquore using the defaultFileBrowserlsquos site without having changed its storage engine In the next major release of FileBrowser thesesettings will be removed

StorageMixin Class

A FileBrowser uses the Djangorsquos Storage class to access media files However the API of the Storageclass does not provide all methods necessary for FileBrowserrsquos functionality A StorageMixin class fromfilebrowserstorage module therefore defines all the additional methods that a FileBrowser requires

isdir(self name)Returns true if name exists and is a directory

41 Admin Interface 25

Django FileBrowser Documentation Release 357

isfile(self name)Returns true if name exists and is a regular file

move(self old_file_name new_file_name allow_overwrite=False)Moves safely a file from one location to another If allow_ovewrite==False and new_file_nameexists raises an exception

makedirs(self name)Creates all missing directories specified by name Analogue to osmkdirs()

414 Views

All views use the staff_member_requird and path_exists decorator in order to check if the server pathactually exists Some views also use the file_exists decorator

bull Browse fb_browse Browse a directory on your server Returns a FileListing

ndash Optional query string args dir o ot q p filter_date filter_type type

bull Create directory fb_createdir Create a new folder on your server

ndash Optional query string args dir

ndash Signals filebrowser_pre_createdir filebrowser_post_createdir

bull Upload fb_upload Multiple upload

ndash Optional query string args dir type

ndash Signals filebrowser_pre_upload filebrowser_post_upload

bull Edit fb_edit Edit a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_rename filebrowser_post_rename

You are able to apply custom actions (see Custom Actions) to the edit-view

bull Confirm delete fb_confirm_delete Confirm the deletion of a file or folder

ndash Required query string args filename

ndash Optional query string args dir

If you try to delete a folder all filesfolders within this folder are listed on this page

bull Delete fb_delete Delete a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_delete filebrowser_post_delete

Warning If you delete a Folder all items within this Folder are being deleted

bull Version fb_version Generate a version of an image as defined with ADMIN_VERSIONS

ndash Required query string args filename

ndash Optional Query string args dir

This is a helper used by the FileBrowseField and TinyMCE for selecting a version

26 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

415 Signals

The FileBrowser sends a couple of different signals Please take a look at the module filebrowsersignals for furtherexplanation on the provided arguments

bull filebrowser_pre_upload Sent before a an Upload starts

bull filebrowser_post_upload Sent after an Upload has finished

bull filebrowser_pre_delete Sent before an Item (File Folder) is deleted

bull filebrowser_post_delete Sent after an Item (File Folder) has been deleted

bull filebrowser_pre_createdir Sent before a new Folder is created

bull filebrowser_post_createdir Sent after a new Folder has been created

bull filebrowser_pre_rename Sent before an Item (File Folder) is renamed

bull filebrowser_post_rename Sent after an Item (File Folder) has been renamed

bull filebrowser_actions_pre_apply Sent before a custom action is applied

bull filebrowser_actions_post_apply Sent after a custom action has been applied

Example for using these Signals

Herersquos a small example for using the above Signals

from filebrowser import signals

def pre_upload_callback(sender kwargs)Receiver function called before an upload startsprint Pre Upload Callbackprint kwargs kwargs

signalsfilebrowser_pre_uploadconnect(pre_upload_callback)

def post_upload_callback(sender kwargs)Receiver function called each time an upload has finishedprint Post Upload Callbackprint kwargs kwargs You can use all attributes available with the FileObject This is just an example print Filesize kwargs[file]filesizeprint Orientation kwargs[file]orientationprint Extension kwargs[file]extension

signalsfilebrowser_post_uploadconnect(post_upload_callback)

41 Admin Interface 27

Django FileBrowser Documentation Release 357

28 Chapter 4 Admin Interface

CHAPTER 5

Image Versions

51 Versions

With the FileBrowser you are able to define different versionssizes for images This enables you to save an originalimage on your server while having different versions of that image to automatically fit your websites grid Versionsare also useful for responsiveadaptive layouts

511 Defining Versions

New in version 340 methods

First you need to know which versionssizes of an image yoursquod like to generate with your website Letrsquos say yoursquoreusing a 12 column grid with 60px for each column and 20px margin (which is a total of 940px) With this grid youcould (for example) define these image versions

FILEBROWSER_VERSIONS_BASEDIR = _versionsFILEBROWSER_VERSIONS =

admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

Use the methods argument if you need to add a filter

def grayscale(im)Convert image to grayscaleif immode = L

im = imconvert(L)return im

FILEBROWSER_VERSIONS = big verbose_name Big (6 col) width 460 height opts methods [grayscale]

)

29

Django FileBrowser Documentation Release 357

512 Versions and the Admin

When using the FileBrowser with the admin interface you need to define ADMIN_VERSIONS andADMIN_THUMBNAIL (see Settings) ADMIN_VERSIONS are available with the admin ie you are able to seethese versions with the image detail view and you are able to select the versions with the FileBrowseField model field

FILEBROWSER_ADMIN_VERSIONS = [thumbnail small medium big large]FILEBROWSER_ADMIN_THUMBNAIL = admin_thumbnail

513 Versions and the Frontend

With your templates you have two different tags to choose from version and version_object With bothtags the version will be generated if it doesnrsquot already exist OR if the original image is newer than the version Inorder to update an image you just overwrite the original image and the versions will be generated automatically (asyou request them within your template)

A Model example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 blank=True null=True)

With your templates use version if you simply need to retrieve the URL or version_object if you need to geta FileObject

lt-- load filebrowser templatetags --gt load fb_versions

lt-- get the url with version --gtltimg src= version blogentryimage medium gt

lt-- get a fileobject with version_object --gt version_object blogentryimage medium as version_medium version_mediumwidth ltimg src= version_medium gt

Templatetag version

RetrievesGenerates a version and returns an URL

version modelfield_name version_prefix

Templatetag version_object

RetrievesGenerates a version and returns a FileObject

version_object modelfield_name version_prefix as variable

Note With both templatetags version_prefix can either be a string or a variable If version_prefix is astring use quotes

30 Chapter 5 Image Versions

Django FileBrowser Documentation Release 357

514 Versions in Views

If you have a FileObject you can generateretrieve a version with

v = objimageversion_generate(version_prefix) returns a FileObject

515 Placeholder

When developing on a locale machine or a development-server you might not have all the images (resp media-files)available that are on your production instance and downloading these files on a regular basis might not be an option

In that case you can use a placeholder instead of a version You just need to define the PLACEHOLDER and overwritethe settings SHOW_PLACEHOLDER andor FORCE_PLACEHOLDER (see Placeholder)

516 Management Commands

fb_version_generateIf you need to generate certain (or all) versions type

python managepy fb_version_generate

fb_version_removeIf you need to generate certain (or all) versions type

python managepy fb_version_generate

Warning Please be very careful with this command

51 Versions 31

Django FileBrowser Documentation Release 357

32 Chapter 5 Image Versions

CHAPTER 6

Help

61 Help

611 FAQ

Why should I use the FileBrowser

If you need your editors or customers to manage files the FileBrowser is an alternative to an FTP-client Moreoveryou are able to define different image versions according to your websites grid Alternatives to the FileBrowser can befound at httpdjangopackagescomgridsgfile-managers

Do I need Grappelli

Grappelli is a requirement for using the FileBrowser There are several filebrowser-no-grappelli repositories (most ofthem on GitHub) but we donrsquot follow the development

I need help

see Troubleshooting

Why are there no fancy effects

The FileBrowser is about managing files We think that you should prepare your files before uploading them to theserver

How do I upload to another server

Use a custom storage engine see httpsdocsdjangoprojectcomen16howtocustom-file-storage

Why do I need image-versions

You need image-versions if your website is based on a grid

33

Django FileBrowser Documentation Release 357

Is the FileBrowser stable

Wersquove developed the FileBrowser for a couple of years and use it with almost all of our clients That said Grappelli isthe more stable and mature application

How can I contribute

Help is very much needed and appreciated Test the FileBrowser and submit feedbackpatches

Who develops the FileBrowser

The FileBrowser is developed and maintained by Patrick Kranzlmuumlller amp Axel Swoboda of vonautomatisch

612 Troubleshooting

Check your setup

Please check if the problem is caused by your setup

bull Read Quick start guide

bull Check if the staticmedia-files are served correctly

bull Make sure you have removed all custom FileBrowser templates from all locations in TEMPLATE_DIRS orcheck that these templates are compatible with the FileBrowser

Run the tests

Start the shell and type

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Check issues

If your setup is fine please check if your problem is a known issue

bull Take a look at all FileBrowser Issues (incuding closed) and search the FileBrowser Google-Group

Add a ticket

If you think yoursquove found a bug please add a ticket

bull Try to describe your problem as precisely as possible

bull Tell us what you did in order to solve the problem

bull Tell us what version of the FileBrowser you are using

bull Tell us what version of Django you are using

34 Chapter 6 Help

Django FileBrowser Documentation Release 357

bull Please do NOT add tickets if yoursquore having problems with serving staticmedia-files (because this is not relatedto the FileBrowser)

bull Please do NOT add tickets referring to Djangos trunk version

bull At best add a patch

Note Be aware that we may close issues not following these guidlines without further notifications

613 Translation

Translation is done via Transifex

Supported Languages

see httpswwwtransifexnetprojectspdjango-filebrowserresourcedjangopo

614 FileBrowser 35 Release Notes

FileBrowser 35 is compatible with Django 14151617 as well as Grappelli 242526

Update from FileBrowser 34x

bull Update Django to 14151617 and check httpsdocsdjangoprojectcomendevreleases14 orhttpsdocsdjangoprojectcomendevreleases15 or httpsdocsdjangoprojectcomendevreleases16

bull Update Grappelli to 24x25x26x

bull Update FileBrowser to 35x

62 Changelog

621 358 (not yet released)

622 357 (September 10th 2014)

bull New Compatibility with Django 17 and Grappelli 26x

bull Improved Updated tests because of the new random suffix with get_available_name (django storage)

bull Improved Added an icon in order to mark finished uploads

bull Improved Show resulting filename (eg with suffix converted) after successful upload

bull Fixed Permissions with file upload

bull Fixed Unified json response with _upload_file (no matter if file already exists or not)

623 356 (April 16th 2014)

bull Fixed Displaying pagination correctly with lots of entries

62 Changelog 35

Django FileBrowser Documentation Release 357

624 355 (April 13th 2014)

bull New Added client-side (JavaScript) file extension validation to the AJAX uploader

bull New Added experimental Python 33 support

bull Improved Tests with convertnormalize (removed special chars from test filename)

bull Fixed File selection after using search box (CKEditor)

bull Fixed Removed encoding of file URIs with CKEditor

625 354 (February 21st 2014)

bull Fixed Placeholder functionality (including tests)

bull Fixed Convertnormalize filenames (including tests)

bull Fixed Handling uppercase extensions with browse

626 353 (January 7 2014)

bull New added path_full to FileObject

bull Improved added docx to EXTENSIONS

bull Improved Recommend pillow instead of PIL as a requirement

bull Improved Added additional test cases

bull Improved Updated documentation

bull Improved Consistent use of storage (eg storagelocation storageurl)

bull Improved Removed unnecessary functions (eg url_join url_strip)

bull Improved Moved sort_by_attr to FileListing

bull Improved Regex matches with file versions on browse

bull Improved Using djangoconfurls (with djangoconfurlsdefaults as fallback)

bull Improved Adding CONTRIBUTINGrst

bull Improved Removed static Media inner class with fields

bull Improved Removed search icon with fields (has not being used)

bull Improved Added custom class attributes with filebrowser field

bull Improved Updated translations

bull Fixed fixed exception handling with python 25

bull Fixed fixes dir with SEARCH_TRAVERSE true and version select

bull Fixed Make Django FileUploadHandlers work (also fixed a memory leak)

bull Fixed return correct filename with OVERWRITE_EXISTING

bull Fixed fb_version_generate with FILEBROWSER_VERSIONS_BASEDIR

bull Fixed Table sorting with ascdesc

bull Fixed Added DeprecationWarning for FileObjectdirectory and FileObjectfolder

36 Chapter 6 Help

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

Django FileBrowser Documentation Release 357

dateDate based on timemktime

gtgtgt fileobjectdate12997603470

datetimeDatetime object

gtgtgt fileobjectdatetimedatetimedatetime(2011 3 10 13 32 27)

existsTrue if the path exists False otherwise

gtgtgt fileobjectexistsTrue

Path and URL attributes

pathPath relative to a storage location (including sitedirectory)

gtgtgt fileobjectpathuploadstestfoldertestimagejpg

path_relative_directoryPath relative to sitedirectory

gtgtgt fileobjectpath_relative_directorytestfoldertestimagejpg

path_fullAbsolute server path (based on storagepath)

gtgtgt fileobjectpath_fullabsolutepathtoserverlocationtestfoldertestimagejpg

dirnameNew in version 34

The directory (not including sitedirectory)

gtgtgt fileobjectdirnametestfolder

urlURL for the filefolder (based on storageurl)

gtgtgt fileobjecturlmediauploadstestfoldertestimagejpg

Image attributes

The image attributes are only useful if the FileObject represents an image

dimensionsImage dimensions as a tuple

21 API 15

Django FileBrowser Documentation Release 357

gtgtgt fileobjectdimensions(1000 750)

widthImage width in px

gtgtgt fileobjectwidth1000

heightImage height in px

gtgtgt fileobjectheight750

aspectratioAspect ratio (float format)

gtgtgt fileobjectaspectratio133534908

orientationImage orientation either Landscape or Portrait

gtgtgt fileobjectorientationLandscape

Folder attributes

The folder attributes make sense when the FileObject represents a directory (not a file)

directory

Deprecated since version 353 Use path_relative_directory instead

folder

Deprecated since version 353 Use dirname instead

is_folderTrue if path is a folder

gtgtgt fileobjectis_folderFalse

is_emptyTrue if the folder is empty False if the folder is not empty or the FileObject is not a folder

gtgtgt fileobjectis_emptyFalse

Version attributes

is_versiontrue if the File is a version of another File

16 Chapter 2 API

Django FileBrowser Documentation Release 357

gtgtgt fileobjectis_versionFalsegtgtgt versionis_versionTrue

versions_basedirThe relative path (from storage location) to the main versions folder Either VERSIONS_BASEDIR orsitedirectory

gtgtgt fileobjectversions_basedir_versionsgtgtgt versionversions_basedir_versions

originalReturns the original FileObject

gtgtgt fileobjectoriginalltFileObject uploadstestfoldertestimagejpggtgtgtgt versionoriginalltFileObject uploadstestfoldertestimagejpggt

original_filenameGet the filename of an original image from a version

gtgtgt fileobjectoriginal_filenametestimagejpggtgtgt versionoriginal_filenametestimagejpg

Methods

Version methods

versions()List all filenames based on VERSIONS

gtgtgt fileobjectversions()[_versionstestfoldertestimage_admin_thumbnailjpg_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionversions()[]

Note The versions are not being generated

admin_versions()List all filenames based on ADMIN_VERSIONS

gtgtgt fileobjectadmin_versions()[_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg

21 API 17

Django FileBrowser Documentation Release 357

_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionadmin_versions()[]

Note The versions are not being generated

version_name(version_suffix)Get the filename for a version

gtgtgt fileobjectversion_name(medium)testimage_mediumjpg

Note The version is not being generated

version_path(version_suffix)Get the path for a version

gtgtgt fileobjectversion_path(medium)_versionstestfoldertestimage_mediumjpg

Note The version is not being generated

version_generate(version_suffix)Generate a version

gtgtgt fileobjectversion_generate(medium)ltFileObject uploadstestfoldertestimage_mediumjpggt

Please note that a version is only generated if it does not already exist or if the original image is newer than theexisting version

Delete methods

delete()Delete the File or Folder from the server

Warning If you delete a Folder all items within the folder are being deleted

delete_versions()Delete all VERSIONS

delete_admin_versions()Delete all ADMIN_VERSIONS

18 Chapter 2 API

CHAPTER 3

Fields amp Widgets

31 Fields amp Widgets

The FileBrowseField is a custom model field which returns a FileObject The widgets FileInput and ClearableFileIn-put are used with the admin app in order to show an additional thumbnail for images

311 FileBrowseField

class FileBrowseField(max_length[ site directory extensions format options])A subclass of CharField referencing a media file within Returns a FileObject

Parameters

bull site ndash A FileBrowser site (defaults to the main site) see FileBrowser Site

bull directory ndash Directory to browse when clicking the search icon

bull extensions ndash List of allowed extensions see Extensions and Formats

bull format ndash A key from SELECT_FORMATS in order to restrict the selection to specificfiletypes see Extensions and Formats

For example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 directory=images extensions=[jpg] blank=True null=True)document = FileBrowseField(PDF max_length=200 directory=documents extensions=[pdfdoc] blank=True null=True)

FileBrowseField in Templates

You can use all attributes from FileObject

blogentryimage ltimg src= publicationimageurl gt

ifequal blogentryimageimage_orientation landscape ltimg src= blogentryimageurl class=landscape gt

endifequal

19

Django FileBrowser Documentation Release 357

Showing Thumbnail in the Changelist

To show a thumbnail with the changelist you can define a ModelAdmin method

from filebrowsersettings import ADMIN_THUMBNAIL

def image_thumbnail(self obj)if objimage and objimagefiletype == Image

return ltimg src=s gt objimageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Using the FileBrowseField with TinyMCE

In order to replace the TinyMCE imagefile manager with the FileBrowser you have to use a FileBrowser CallbackTherersquos an example TinyMCE configuration file in staticjs called TinyMCEAdminjs You can either copy theFileBrowserCallback to your own file or just use tinymce_setupjs (which comes with django-grappelli)

Just add these lines to your ModelAdmin asset definitions

class Mediajs = [pathtotinymcejscriptstiny_mcetiny_mcejs

pathtoyourtinymce_setupjs]

312 FileInput

Subclass of FileInput with an additional thumbnail

from filebrowserwidgets import FileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget FileInput

313 ClearableFileInput

Subclass of ClearableFileInput with an additional thumbnail

from filebrowserwidgets import ClearableFileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget ClearableFileInput

314 Django FileField and the FileBrowser

Return a FileObject from a FileField or ImageField with

20 Chapter 3 Fields amp Widgets

Django FileBrowser Documentation Release 357

from filebrowserbase import FileObject

image_upload = modelsImageField(uImage (Upload) max_length=250 upload_to=image_upload_path blank=True null=True)

def image(self)if selfimage_upload

return FileObject(selfimage_uploadpath)return None

In order show a thumbnail with your changelist you could use a ModelAdmin method

from filebrowserbase import FileObject

def image_thumbnail(self obj)if objimage_upload

image = FileObject(objimage_uploadpath)if imagefiletype == Image

return ltimg src=s gt imageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Note There are different ways to achieve this The above examples show one of several options

31 Fields amp Widgets 21

Django FileBrowser Documentation Release 357

22 Chapter 3 Fields amp Widgets

CHAPTER 4

Admin Interface

41 Admin Interface

The main FileBrowser admin application is an extension for the Django admin interface in order to browser yourmedia folder upload and renamedelete files

411 FileBrowser Site

New in version 340

class FileBrowserSite(name=None app_name=rsquofilebrowserrsquo storage=default_storage)Respresents the FileBrowser admin application (similar to Djangorsquos admin site)

Parameters

bull name ndash A name for the site defaults to None

bull app_name ndash Defaults to lsquofilebrowserrsquo

bull storage ndash A custom storage engine defaults to Djangos default storage

Similar to djangocontribadmin you first need to add a filebrowsersite to your admin interface Inyour urlspy import the default FileBrowser site (or your custom site) and add the site to your URL-patterns (beforeany admin-urls)

from filebrowsersites import site

urlpatterns = patterns(url(r^adminurlfilebrowser include(siteurls))

)

Now you are able to browse the location defined with the storage engine associated to your site

from djangocorefilesstorage import DefaultStoragefrom filebrowsersites import FileBrowserSite

Default FileBrowser sitesite = FileBrowserSite(name=filebrowser storage=DefaultStorage())

My Custom FileBrowser sitecustom_site = FileBrowserSite(name=custom_filebrowser storage=DefaultStorage())custom_sitedirectory = custom_uploads

23

Django FileBrowser Documentation Release 357

Note The module variable site from filebrowsersites is the default FileBrowser application

412 Custom Actions

New in version 340

Similar to Djangorsquos admin actions you can define your FileBrowser actions and thus automate the typical tasks ofyour users Registered custom actions are listed in the detail view of a file and a user can select a single action at atime The selected action will then be applied to the file

The default FileBrowser image actions such as ldquoFlip Verticalrdquo or ldquoRotate 90deg Clockwiserdquo are in fact implemented ascustom actions (see the module filebrowseractions)

Writing Your Own Actions

Custom actions are simple functions

def foo(request fileobjects) Do something with the fileobjects

The first parameter is a HttpRequest object (representing the submitted form in which a user selected the action)and the second parameter is a list of FileObjects to which the action should be applied

The list contains exactly one instance of FileObject (representing the file from the detail view) but this may change inthe future as custom actions may become available also in browse views (similar to admin actions applied to a list ofchecked objects)

Registering an Action

In order to make your action visible you need to register it with a FileBrowser site

siteadd_action(foo)

Once registered the action will appear in the detail view of a file You can also give your action a short description

fooshort_description = Do foo with the File

This short description will then appear in the list of available actions If you do not provide a short description thefunction name will be used instead and FileBrowser will replace any underscores in the function name with spaces

Associating Actions with Specific Files

Each custom action can be associated with a specific file type (eg images audio file etc) to which it applies In orderto do that you need to define a predicatefilter function which takes a single argument (FileObject) and returns Trueif your action is applicable to that FileObject Finally you need to register this filter function with your action

fooapplies_to(lambda fileobject fileobjectfiletype == Image)

In the above example foo will appear in the action list only for image files If you do not specify any filter functionfor your action FileBrowser considers the action as applicable to all files

24 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

Messages amp Intermediate Pages

You can provide a feedback to a user about a successful or failed execution of an action by using a message Forexample

from djangocontrib import messages

def desaturate_image(request fileobjects)for f in fileobjects

Desaturate the imagemessagesadd_message(request messagesSUCCESS _(Image s was desaturated) ffilename)

Some actions may require user confirmation (eg in order to prevent accidental and irreversible modification tofiles) In order to that follow the same pattern as with Djangorsquos admin action and return a HttpResponse objectfrom your action Good practice for intermediate pages is to implement a confirm view and have your action returnHttpResponseRedirect

def crop_image(request fileobjects)files = ampf=join([fpath_relative for f in fileobjects])return HttpResponseRedirect(confirmaction=crop_imageampf=s files)

413 File Storages

New in version 340

You have the option to specify which file storage engine a FileBrowser should use to browseuploadmodify yourmedia files This enables you to use a FileBrowser even if your media files are located at some remote system Seealso the Djangorsquos documentation on storages httpsdocsdjangoprojectcomendevtopicsfiles

To associate a FileBrowser site with a particular storage engine set the storage property of a site object

from djangocorefilesstorage import FileSystemStoragesitestorage = FileSystemStorage(location=pathtomediadirectory base_url=media)

For storage classes other than FileSystemStorage (or those that inherit from that class) therersquos more effort involved inproviding a storage object that can be used with FileBrowser See StorageMixin Class

Note Prior FileBrowser 34 the way to specify FileBrowserlsquos MEDIA_ROOT and MEDIA_URL was via settingspyStarting from version 34 those variables are associated with the storage instance and you can set them as illustratedin the above example

Warning For the reason of backward compatibility FileBrowser settings FILEBROWSER_MEDIA_ROOT andFILEBROWSER_MEDIA_URL can still be used to customize FileBrowser as long as yoursquore using the defaultFileBrowserlsquos site without having changed its storage engine In the next major release of FileBrowser thesesettings will be removed

StorageMixin Class

A FileBrowser uses the Djangorsquos Storage class to access media files However the API of the Storageclass does not provide all methods necessary for FileBrowserrsquos functionality A StorageMixin class fromfilebrowserstorage module therefore defines all the additional methods that a FileBrowser requires

isdir(self name)Returns true if name exists and is a directory

41 Admin Interface 25

Django FileBrowser Documentation Release 357

isfile(self name)Returns true if name exists and is a regular file

move(self old_file_name new_file_name allow_overwrite=False)Moves safely a file from one location to another If allow_ovewrite==False and new_file_nameexists raises an exception

makedirs(self name)Creates all missing directories specified by name Analogue to osmkdirs()

414 Views

All views use the staff_member_requird and path_exists decorator in order to check if the server pathactually exists Some views also use the file_exists decorator

bull Browse fb_browse Browse a directory on your server Returns a FileListing

ndash Optional query string args dir o ot q p filter_date filter_type type

bull Create directory fb_createdir Create a new folder on your server

ndash Optional query string args dir

ndash Signals filebrowser_pre_createdir filebrowser_post_createdir

bull Upload fb_upload Multiple upload

ndash Optional query string args dir type

ndash Signals filebrowser_pre_upload filebrowser_post_upload

bull Edit fb_edit Edit a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_rename filebrowser_post_rename

You are able to apply custom actions (see Custom Actions) to the edit-view

bull Confirm delete fb_confirm_delete Confirm the deletion of a file or folder

ndash Required query string args filename

ndash Optional query string args dir

If you try to delete a folder all filesfolders within this folder are listed on this page

bull Delete fb_delete Delete a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_delete filebrowser_post_delete

Warning If you delete a Folder all items within this Folder are being deleted

bull Version fb_version Generate a version of an image as defined with ADMIN_VERSIONS

ndash Required query string args filename

ndash Optional Query string args dir

This is a helper used by the FileBrowseField and TinyMCE for selecting a version

26 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

415 Signals

The FileBrowser sends a couple of different signals Please take a look at the module filebrowsersignals for furtherexplanation on the provided arguments

bull filebrowser_pre_upload Sent before a an Upload starts

bull filebrowser_post_upload Sent after an Upload has finished

bull filebrowser_pre_delete Sent before an Item (File Folder) is deleted

bull filebrowser_post_delete Sent after an Item (File Folder) has been deleted

bull filebrowser_pre_createdir Sent before a new Folder is created

bull filebrowser_post_createdir Sent after a new Folder has been created

bull filebrowser_pre_rename Sent before an Item (File Folder) is renamed

bull filebrowser_post_rename Sent after an Item (File Folder) has been renamed

bull filebrowser_actions_pre_apply Sent before a custom action is applied

bull filebrowser_actions_post_apply Sent after a custom action has been applied

Example for using these Signals

Herersquos a small example for using the above Signals

from filebrowser import signals

def pre_upload_callback(sender kwargs)Receiver function called before an upload startsprint Pre Upload Callbackprint kwargs kwargs

signalsfilebrowser_pre_uploadconnect(pre_upload_callback)

def post_upload_callback(sender kwargs)Receiver function called each time an upload has finishedprint Post Upload Callbackprint kwargs kwargs You can use all attributes available with the FileObject This is just an example print Filesize kwargs[file]filesizeprint Orientation kwargs[file]orientationprint Extension kwargs[file]extension

signalsfilebrowser_post_uploadconnect(post_upload_callback)

41 Admin Interface 27

Django FileBrowser Documentation Release 357

28 Chapter 4 Admin Interface

CHAPTER 5

Image Versions

51 Versions

With the FileBrowser you are able to define different versionssizes for images This enables you to save an originalimage on your server while having different versions of that image to automatically fit your websites grid Versionsare also useful for responsiveadaptive layouts

511 Defining Versions

New in version 340 methods

First you need to know which versionssizes of an image yoursquod like to generate with your website Letrsquos say yoursquoreusing a 12 column grid with 60px for each column and 20px margin (which is a total of 940px) With this grid youcould (for example) define these image versions

FILEBROWSER_VERSIONS_BASEDIR = _versionsFILEBROWSER_VERSIONS =

admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

Use the methods argument if you need to add a filter

def grayscale(im)Convert image to grayscaleif immode = L

im = imconvert(L)return im

FILEBROWSER_VERSIONS = big verbose_name Big (6 col) width 460 height opts methods [grayscale]

)

29

Django FileBrowser Documentation Release 357

512 Versions and the Admin

When using the FileBrowser with the admin interface you need to define ADMIN_VERSIONS andADMIN_THUMBNAIL (see Settings) ADMIN_VERSIONS are available with the admin ie you are able to seethese versions with the image detail view and you are able to select the versions with the FileBrowseField model field

FILEBROWSER_ADMIN_VERSIONS = [thumbnail small medium big large]FILEBROWSER_ADMIN_THUMBNAIL = admin_thumbnail

513 Versions and the Frontend

With your templates you have two different tags to choose from version and version_object With bothtags the version will be generated if it doesnrsquot already exist OR if the original image is newer than the version Inorder to update an image you just overwrite the original image and the versions will be generated automatically (asyou request them within your template)

A Model example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 blank=True null=True)

With your templates use version if you simply need to retrieve the URL or version_object if you need to geta FileObject

lt-- load filebrowser templatetags --gt load fb_versions

lt-- get the url with version --gtltimg src= version blogentryimage medium gt

lt-- get a fileobject with version_object --gt version_object blogentryimage medium as version_medium version_mediumwidth ltimg src= version_medium gt

Templatetag version

RetrievesGenerates a version and returns an URL

version modelfield_name version_prefix

Templatetag version_object

RetrievesGenerates a version and returns a FileObject

version_object modelfield_name version_prefix as variable

Note With both templatetags version_prefix can either be a string or a variable If version_prefix is astring use quotes

30 Chapter 5 Image Versions

Django FileBrowser Documentation Release 357

514 Versions in Views

If you have a FileObject you can generateretrieve a version with

v = objimageversion_generate(version_prefix) returns a FileObject

515 Placeholder

When developing on a locale machine or a development-server you might not have all the images (resp media-files)available that are on your production instance and downloading these files on a regular basis might not be an option

In that case you can use a placeholder instead of a version You just need to define the PLACEHOLDER and overwritethe settings SHOW_PLACEHOLDER andor FORCE_PLACEHOLDER (see Placeholder)

516 Management Commands

fb_version_generateIf you need to generate certain (or all) versions type

python managepy fb_version_generate

fb_version_removeIf you need to generate certain (or all) versions type

python managepy fb_version_generate

Warning Please be very careful with this command

51 Versions 31

Django FileBrowser Documentation Release 357

32 Chapter 5 Image Versions

CHAPTER 6

Help

61 Help

611 FAQ

Why should I use the FileBrowser

If you need your editors or customers to manage files the FileBrowser is an alternative to an FTP-client Moreoveryou are able to define different image versions according to your websites grid Alternatives to the FileBrowser can befound at httpdjangopackagescomgridsgfile-managers

Do I need Grappelli

Grappelli is a requirement for using the FileBrowser There are several filebrowser-no-grappelli repositories (most ofthem on GitHub) but we donrsquot follow the development

I need help

see Troubleshooting

Why are there no fancy effects

The FileBrowser is about managing files We think that you should prepare your files before uploading them to theserver

How do I upload to another server

Use a custom storage engine see httpsdocsdjangoprojectcomen16howtocustom-file-storage

Why do I need image-versions

You need image-versions if your website is based on a grid

33

Django FileBrowser Documentation Release 357

Is the FileBrowser stable

Wersquove developed the FileBrowser for a couple of years and use it with almost all of our clients That said Grappelli isthe more stable and mature application

How can I contribute

Help is very much needed and appreciated Test the FileBrowser and submit feedbackpatches

Who develops the FileBrowser

The FileBrowser is developed and maintained by Patrick Kranzlmuumlller amp Axel Swoboda of vonautomatisch

612 Troubleshooting

Check your setup

Please check if the problem is caused by your setup

bull Read Quick start guide

bull Check if the staticmedia-files are served correctly

bull Make sure you have removed all custom FileBrowser templates from all locations in TEMPLATE_DIRS orcheck that these templates are compatible with the FileBrowser

Run the tests

Start the shell and type

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Check issues

If your setup is fine please check if your problem is a known issue

bull Take a look at all FileBrowser Issues (incuding closed) and search the FileBrowser Google-Group

Add a ticket

If you think yoursquove found a bug please add a ticket

bull Try to describe your problem as precisely as possible

bull Tell us what you did in order to solve the problem

bull Tell us what version of the FileBrowser you are using

bull Tell us what version of Django you are using

34 Chapter 6 Help

Django FileBrowser Documentation Release 357

bull Please do NOT add tickets if yoursquore having problems with serving staticmedia-files (because this is not relatedto the FileBrowser)

bull Please do NOT add tickets referring to Djangos trunk version

bull At best add a patch

Note Be aware that we may close issues not following these guidlines without further notifications

613 Translation

Translation is done via Transifex

Supported Languages

see httpswwwtransifexnetprojectspdjango-filebrowserresourcedjangopo

614 FileBrowser 35 Release Notes

FileBrowser 35 is compatible with Django 14151617 as well as Grappelli 242526

Update from FileBrowser 34x

bull Update Django to 14151617 and check httpsdocsdjangoprojectcomendevreleases14 orhttpsdocsdjangoprojectcomendevreleases15 or httpsdocsdjangoprojectcomendevreleases16

bull Update Grappelli to 24x25x26x

bull Update FileBrowser to 35x

62 Changelog

621 358 (not yet released)

622 357 (September 10th 2014)

bull New Compatibility with Django 17 and Grappelli 26x

bull Improved Updated tests because of the new random suffix with get_available_name (django storage)

bull Improved Added an icon in order to mark finished uploads

bull Improved Show resulting filename (eg with suffix converted) after successful upload

bull Fixed Permissions with file upload

bull Fixed Unified json response with _upload_file (no matter if file already exists or not)

623 356 (April 16th 2014)

bull Fixed Displaying pagination correctly with lots of entries

62 Changelog 35

Django FileBrowser Documentation Release 357

624 355 (April 13th 2014)

bull New Added client-side (JavaScript) file extension validation to the AJAX uploader

bull New Added experimental Python 33 support

bull Improved Tests with convertnormalize (removed special chars from test filename)

bull Fixed File selection after using search box (CKEditor)

bull Fixed Removed encoding of file URIs with CKEditor

625 354 (February 21st 2014)

bull Fixed Placeholder functionality (including tests)

bull Fixed Convertnormalize filenames (including tests)

bull Fixed Handling uppercase extensions with browse

626 353 (January 7 2014)

bull New added path_full to FileObject

bull Improved added docx to EXTENSIONS

bull Improved Recommend pillow instead of PIL as a requirement

bull Improved Added additional test cases

bull Improved Updated documentation

bull Improved Consistent use of storage (eg storagelocation storageurl)

bull Improved Removed unnecessary functions (eg url_join url_strip)

bull Improved Moved sort_by_attr to FileListing

bull Improved Regex matches with file versions on browse

bull Improved Using djangoconfurls (with djangoconfurlsdefaults as fallback)

bull Improved Adding CONTRIBUTINGrst

bull Improved Removed static Media inner class with fields

bull Improved Removed search icon with fields (has not being used)

bull Improved Added custom class attributes with filebrowser field

bull Improved Updated translations

bull Fixed fixed exception handling with python 25

bull Fixed fixes dir with SEARCH_TRAVERSE true and version select

bull Fixed Make Django FileUploadHandlers work (also fixed a memory leak)

bull Fixed return correct filename with OVERWRITE_EXISTING

bull Fixed fb_version_generate with FILEBROWSER_VERSIONS_BASEDIR

bull Fixed Table sorting with ascdesc

bull Fixed Added DeprecationWarning for FileObjectdirectory and FileObjectfolder

36 Chapter 6 Help

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

Django FileBrowser Documentation Release 357

gtgtgt fileobjectdimensions(1000 750)

widthImage width in px

gtgtgt fileobjectwidth1000

heightImage height in px

gtgtgt fileobjectheight750

aspectratioAspect ratio (float format)

gtgtgt fileobjectaspectratio133534908

orientationImage orientation either Landscape or Portrait

gtgtgt fileobjectorientationLandscape

Folder attributes

The folder attributes make sense when the FileObject represents a directory (not a file)

directory

Deprecated since version 353 Use path_relative_directory instead

folder

Deprecated since version 353 Use dirname instead

is_folderTrue if path is a folder

gtgtgt fileobjectis_folderFalse

is_emptyTrue if the folder is empty False if the folder is not empty or the FileObject is not a folder

gtgtgt fileobjectis_emptyFalse

Version attributes

is_versiontrue if the File is a version of another File

16 Chapter 2 API

Django FileBrowser Documentation Release 357

gtgtgt fileobjectis_versionFalsegtgtgt versionis_versionTrue

versions_basedirThe relative path (from storage location) to the main versions folder Either VERSIONS_BASEDIR orsitedirectory

gtgtgt fileobjectversions_basedir_versionsgtgtgt versionversions_basedir_versions

originalReturns the original FileObject

gtgtgt fileobjectoriginalltFileObject uploadstestfoldertestimagejpggtgtgtgt versionoriginalltFileObject uploadstestfoldertestimagejpggt

original_filenameGet the filename of an original image from a version

gtgtgt fileobjectoriginal_filenametestimagejpggtgtgt versionoriginal_filenametestimagejpg

Methods

Version methods

versions()List all filenames based on VERSIONS

gtgtgt fileobjectversions()[_versionstestfoldertestimage_admin_thumbnailjpg_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionversions()[]

Note The versions are not being generated

admin_versions()List all filenames based on ADMIN_VERSIONS

gtgtgt fileobjectadmin_versions()[_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg

21 API 17

Django FileBrowser Documentation Release 357

_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionadmin_versions()[]

Note The versions are not being generated

version_name(version_suffix)Get the filename for a version

gtgtgt fileobjectversion_name(medium)testimage_mediumjpg

Note The version is not being generated

version_path(version_suffix)Get the path for a version

gtgtgt fileobjectversion_path(medium)_versionstestfoldertestimage_mediumjpg

Note The version is not being generated

version_generate(version_suffix)Generate a version

gtgtgt fileobjectversion_generate(medium)ltFileObject uploadstestfoldertestimage_mediumjpggt

Please note that a version is only generated if it does not already exist or if the original image is newer than theexisting version

Delete methods

delete()Delete the File or Folder from the server

Warning If you delete a Folder all items within the folder are being deleted

delete_versions()Delete all VERSIONS

delete_admin_versions()Delete all ADMIN_VERSIONS

18 Chapter 2 API

CHAPTER 3

Fields amp Widgets

31 Fields amp Widgets

The FileBrowseField is a custom model field which returns a FileObject The widgets FileInput and ClearableFileIn-put are used with the admin app in order to show an additional thumbnail for images

311 FileBrowseField

class FileBrowseField(max_length[ site directory extensions format options])A subclass of CharField referencing a media file within Returns a FileObject

Parameters

bull site ndash A FileBrowser site (defaults to the main site) see FileBrowser Site

bull directory ndash Directory to browse when clicking the search icon

bull extensions ndash List of allowed extensions see Extensions and Formats

bull format ndash A key from SELECT_FORMATS in order to restrict the selection to specificfiletypes see Extensions and Formats

For example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 directory=images extensions=[jpg] blank=True null=True)document = FileBrowseField(PDF max_length=200 directory=documents extensions=[pdfdoc] blank=True null=True)

FileBrowseField in Templates

You can use all attributes from FileObject

blogentryimage ltimg src= publicationimageurl gt

ifequal blogentryimageimage_orientation landscape ltimg src= blogentryimageurl class=landscape gt

endifequal

19

Django FileBrowser Documentation Release 357

Showing Thumbnail in the Changelist

To show a thumbnail with the changelist you can define a ModelAdmin method

from filebrowsersettings import ADMIN_THUMBNAIL

def image_thumbnail(self obj)if objimage and objimagefiletype == Image

return ltimg src=s gt objimageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Using the FileBrowseField with TinyMCE

In order to replace the TinyMCE imagefile manager with the FileBrowser you have to use a FileBrowser CallbackTherersquos an example TinyMCE configuration file in staticjs called TinyMCEAdminjs You can either copy theFileBrowserCallback to your own file or just use tinymce_setupjs (which comes with django-grappelli)

Just add these lines to your ModelAdmin asset definitions

class Mediajs = [pathtotinymcejscriptstiny_mcetiny_mcejs

pathtoyourtinymce_setupjs]

312 FileInput

Subclass of FileInput with an additional thumbnail

from filebrowserwidgets import FileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget FileInput

313 ClearableFileInput

Subclass of ClearableFileInput with an additional thumbnail

from filebrowserwidgets import ClearableFileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget ClearableFileInput

314 Django FileField and the FileBrowser

Return a FileObject from a FileField or ImageField with

20 Chapter 3 Fields amp Widgets

Django FileBrowser Documentation Release 357

from filebrowserbase import FileObject

image_upload = modelsImageField(uImage (Upload) max_length=250 upload_to=image_upload_path blank=True null=True)

def image(self)if selfimage_upload

return FileObject(selfimage_uploadpath)return None

In order show a thumbnail with your changelist you could use a ModelAdmin method

from filebrowserbase import FileObject

def image_thumbnail(self obj)if objimage_upload

image = FileObject(objimage_uploadpath)if imagefiletype == Image

return ltimg src=s gt imageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Note There are different ways to achieve this The above examples show one of several options

31 Fields amp Widgets 21

Django FileBrowser Documentation Release 357

22 Chapter 3 Fields amp Widgets

CHAPTER 4

Admin Interface

41 Admin Interface

The main FileBrowser admin application is an extension for the Django admin interface in order to browser yourmedia folder upload and renamedelete files

411 FileBrowser Site

New in version 340

class FileBrowserSite(name=None app_name=rsquofilebrowserrsquo storage=default_storage)Respresents the FileBrowser admin application (similar to Djangorsquos admin site)

Parameters

bull name ndash A name for the site defaults to None

bull app_name ndash Defaults to lsquofilebrowserrsquo

bull storage ndash A custom storage engine defaults to Djangos default storage

Similar to djangocontribadmin you first need to add a filebrowsersite to your admin interface Inyour urlspy import the default FileBrowser site (or your custom site) and add the site to your URL-patterns (beforeany admin-urls)

from filebrowsersites import site

urlpatterns = patterns(url(r^adminurlfilebrowser include(siteurls))

)

Now you are able to browse the location defined with the storage engine associated to your site

from djangocorefilesstorage import DefaultStoragefrom filebrowsersites import FileBrowserSite

Default FileBrowser sitesite = FileBrowserSite(name=filebrowser storage=DefaultStorage())

My Custom FileBrowser sitecustom_site = FileBrowserSite(name=custom_filebrowser storage=DefaultStorage())custom_sitedirectory = custom_uploads

23

Django FileBrowser Documentation Release 357

Note The module variable site from filebrowsersites is the default FileBrowser application

412 Custom Actions

New in version 340

Similar to Djangorsquos admin actions you can define your FileBrowser actions and thus automate the typical tasks ofyour users Registered custom actions are listed in the detail view of a file and a user can select a single action at atime The selected action will then be applied to the file

The default FileBrowser image actions such as ldquoFlip Verticalrdquo or ldquoRotate 90deg Clockwiserdquo are in fact implemented ascustom actions (see the module filebrowseractions)

Writing Your Own Actions

Custom actions are simple functions

def foo(request fileobjects) Do something with the fileobjects

The first parameter is a HttpRequest object (representing the submitted form in which a user selected the action)and the second parameter is a list of FileObjects to which the action should be applied

The list contains exactly one instance of FileObject (representing the file from the detail view) but this may change inthe future as custom actions may become available also in browse views (similar to admin actions applied to a list ofchecked objects)

Registering an Action

In order to make your action visible you need to register it with a FileBrowser site

siteadd_action(foo)

Once registered the action will appear in the detail view of a file You can also give your action a short description

fooshort_description = Do foo with the File

This short description will then appear in the list of available actions If you do not provide a short description thefunction name will be used instead and FileBrowser will replace any underscores in the function name with spaces

Associating Actions with Specific Files

Each custom action can be associated with a specific file type (eg images audio file etc) to which it applies In orderto do that you need to define a predicatefilter function which takes a single argument (FileObject) and returns Trueif your action is applicable to that FileObject Finally you need to register this filter function with your action

fooapplies_to(lambda fileobject fileobjectfiletype == Image)

In the above example foo will appear in the action list only for image files If you do not specify any filter functionfor your action FileBrowser considers the action as applicable to all files

24 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

Messages amp Intermediate Pages

You can provide a feedback to a user about a successful or failed execution of an action by using a message Forexample

from djangocontrib import messages

def desaturate_image(request fileobjects)for f in fileobjects

Desaturate the imagemessagesadd_message(request messagesSUCCESS _(Image s was desaturated) ffilename)

Some actions may require user confirmation (eg in order to prevent accidental and irreversible modification tofiles) In order to that follow the same pattern as with Djangorsquos admin action and return a HttpResponse objectfrom your action Good practice for intermediate pages is to implement a confirm view and have your action returnHttpResponseRedirect

def crop_image(request fileobjects)files = ampf=join([fpath_relative for f in fileobjects])return HttpResponseRedirect(confirmaction=crop_imageampf=s files)

413 File Storages

New in version 340

You have the option to specify which file storage engine a FileBrowser should use to browseuploadmodify yourmedia files This enables you to use a FileBrowser even if your media files are located at some remote system Seealso the Djangorsquos documentation on storages httpsdocsdjangoprojectcomendevtopicsfiles

To associate a FileBrowser site with a particular storage engine set the storage property of a site object

from djangocorefilesstorage import FileSystemStoragesitestorage = FileSystemStorage(location=pathtomediadirectory base_url=media)

For storage classes other than FileSystemStorage (or those that inherit from that class) therersquos more effort involved inproviding a storage object that can be used with FileBrowser See StorageMixin Class

Note Prior FileBrowser 34 the way to specify FileBrowserlsquos MEDIA_ROOT and MEDIA_URL was via settingspyStarting from version 34 those variables are associated with the storage instance and you can set them as illustratedin the above example

Warning For the reason of backward compatibility FileBrowser settings FILEBROWSER_MEDIA_ROOT andFILEBROWSER_MEDIA_URL can still be used to customize FileBrowser as long as yoursquore using the defaultFileBrowserlsquos site without having changed its storage engine In the next major release of FileBrowser thesesettings will be removed

StorageMixin Class

A FileBrowser uses the Djangorsquos Storage class to access media files However the API of the Storageclass does not provide all methods necessary for FileBrowserrsquos functionality A StorageMixin class fromfilebrowserstorage module therefore defines all the additional methods that a FileBrowser requires

isdir(self name)Returns true if name exists and is a directory

41 Admin Interface 25

Django FileBrowser Documentation Release 357

isfile(self name)Returns true if name exists and is a regular file

move(self old_file_name new_file_name allow_overwrite=False)Moves safely a file from one location to another If allow_ovewrite==False and new_file_nameexists raises an exception

makedirs(self name)Creates all missing directories specified by name Analogue to osmkdirs()

414 Views

All views use the staff_member_requird and path_exists decorator in order to check if the server pathactually exists Some views also use the file_exists decorator

bull Browse fb_browse Browse a directory on your server Returns a FileListing

ndash Optional query string args dir o ot q p filter_date filter_type type

bull Create directory fb_createdir Create a new folder on your server

ndash Optional query string args dir

ndash Signals filebrowser_pre_createdir filebrowser_post_createdir

bull Upload fb_upload Multiple upload

ndash Optional query string args dir type

ndash Signals filebrowser_pre_upload filebrowser_post_upload

bull Edit fb_edit Edit a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_rename filebrowser_post_rename

You are able to apply custom actions (see Custom Actions) to the edit-view

bull Confirm delete fb_confirm_delete Confirm the deletion of a file or folder

ndash Required query string args filename

ndash Optional query string args dir

If you try to delete a folder all filesfolders within this folder are listed on this page

bull Delete fb_delete Delete a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_delete filebrowser_post_delete

Warning If you delete a Folder all items within this Folder are being deleted

bull Version fb_version Generate a version of an image as defined with ADMIN_VERSIONS

ndash Required query string args filename

ndash Optional Query string args dir

This is a helper used by the FileBrowseField and TinyMCE for selecting a version

26 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

415 Signals

The FileBrowser sends a couple of different signals Please take a look at the module filebrowsersignals for furtherexplanation on the provided arguments

bull filebrowser_pre_upload Sent before a an Upload starts

bull filebrowser_post_upload Sent after an Upload has finished

bull filebrowser_pre_delete Sent before an Item (File Folder) is deleted

bull filebrowser_post_delete Sent after an Item (File Folder) has been deleted

bull filebrowser_pre_createdir Sent before a new Folder is created

bull filebrowser_post_createdir Sent after a new Folder has been created

bull filebrowser_pre_rename Sent before an Item (File Folder) is renamed

bull filebrowser_post_rename Sent after an Item (File Folder) has been renamed

bull filebrowser_actions_pre_apply Sent before a custom action is applied

bull filebrowser_actions_post_apply Sent after a custom action has been applied

Example for using these Signals

Herersquos a small example for using the above Signals

from filebrowser import signals

def pre_upload_callback(sender kwargs)Receiver function called before an upload startsprint Pre Upload Callbackprint kwargs kwargs

signalsfilebrowser_pre_uploadconnect(pre_upload_callback)

def post_upload_callback(sender kwargs)Receiver function called each time an upload has finishedprint Post Upload Callbackprint kwargs kwargs You can use all attributes available with the FileObject This is just an example print Filesize kwargs[file]filesizeprint Orientation kwargs[file]orientationprint Extension kwargs[file]extension

signalsfilebrowser_post_uploadconnect(post_upload_callback)

41 Admin Interface 27

Django FileBrowser Documentation Release 357

28 Chapter 4 Admin Interface

CHAPTER 5

Image Versions

51 Versions

With the FileBrowser you are able to define different versionssizes for images This enables you to save an originalimage on your server while having different versions of that image to automatically fit your websites grid Versionsare also useful for responsiveadaptive layouts

511 Defining Versions

New in version 340 methods

First you need to know which versionssizes of an image yoursquod like to generate with your website Letrsquos say yoursquoreusing a 12 column grid with 60px for each column and 20px margin (which is a total of 940px) With this grid youcould (for example) define these image versions

FILEBROWSER_VERSIONS_BASEDIR = _versionsFILEBROWSER_VERSIONS =

admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

Use the methods argument if you need to add a filter

def grayscale(im)Convert image to grayscaleif immode = L

im = imconvert(L)return im

FILEBROWSER_VERSIONS = big verbose_name Big (6 col) width 460 height opts methods [grayscale]

)

29

Django FileBrowser Documentation Release 357

512 Versions and the Admin

When using the FileBrowser with the admin interface you need to define ADMIN_VERSIONS andADMIN_THUMBNAIL (see Settings) ADMIN_VERSIONS are available with the admin ie you are able to seethese versions with the image detail view and you are able to select the versions with the FileBrowseField model field

FILEBROWSER_ADMIN_VERSIONS = [thumbnail small medium big large]FILEBROWSER_ADMIN_THUMBNAIL = admin_thumbnail

513 Versions and the Frontend

With your templates you have two different tags to choose from version and version_object With bothtags the version will be generated if it doesnrsquot already exist OR if the original image is newer than the version Inorder to update an image you just overwrite the original image and the versions will be generated automatically (asyou request them within your template)

A Model example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 blank=True null=True)

With your templates use version if you simply need to retrieve the URL or version_object if you need to geta FileObject

lt-- load filebrowser templatetags --gt load fb_versions

lt-- get the url with version --gtltimg src= version blogentryimage medium gt

lt-- get a fileobject with version_object --gt version_object blogentryimage medium as version_medium version_mediumwidth ltimg src= version_medium gt

Templatetag version

RetrievesGenerates a version and returns an URL

version modelfield_name version_prefix

Templatetag version_object

RetrievesGenerates a version and returns a FileObject

version_object modelfield_name version_prefix as variable

Note With both templatetags version_prefix can either be a string or a variable If version_prefix is astring use quotes

30 Chapter 5 Image Versions

Django FileBrowser Documentation Release 357

514 Versions in Views

If you have a FileObject you can generateretrieve a version with

v = objimageversion_generate(version_prefix) returns a FileObject

515 Placeholder

When developing on a locale machine or a development-server you might not have all the images (resp media-files)available that are on your production instance and downloading these files on a regular basis might not be an option

In that case you can use a placeholder instead of a version You just need to define the PLACEHOLDER and overwritethe settings SHOW_PLACEHOLDER andor FORCE_PLACEHOLDER (see Placeholder)

516 Management Commands

fb_version_generateIf you need to generate certain (or all) versions type

python managepy fb_version_generate

fb_version_removeIf you need to generate certain (or all) versions type

python managepy fb_version_generate

Warning Please be very careful with this command

51 Versions 31

Django FileBrowser Documentation Release 357

32 Chapter 5 Image Versions

CHAPTER 6

Help

61 Help

611 FAQ

Why should I use the FileBrowser

If you need your editors or customers to manage files the FileBrowser is an alternative to an FTP-client Moreoveryou are able to define different image versions according to your websites grid Alternatives to the FileBrowser can befound at httpdjangopackagescomgridsgfile-managers

Do I need Grappelli

Grappelli is a requirement for using the FileBrowser There are several filebrowser-no-grappelli repositories (most ofthem on GitHub) but we donrsquot follow the development

I need help

see Troubleshooting

Why are there no fancy effects

The FileBrowser is about managing files We think that you should prepare your files before uploading them to theserver

How do I upload to another server

Use a custom storage engine see httpsdocsdjangoprojectcomen16howtocustom-file-storage

Why do I need image-versions

You need image-versions if your website is based on a grid

33

Django FileBrowser Documentation Release 357

Is the FileBrowser stable

Wersquove developed the FileBrowser for a couple of years and use it with almost all of our clients That said Grappelli isthe more stable and mature application

How can I contribute

Help is very much needed and appreciated Test the FileBrowser and submit feedbackpatches

Who develops the FileBrowser

The FileBrowser is developed and maintained by Patrick Kranzlmuumlller amp Axel Swoboda of vonautomatisch

612 Troubleshooting

Check your setup

Please check if the problem is caused by your setup

bull Read Quick start guide

bull Check if the staticmedia-files are served correctly

bull Make sure you have removed all custom FileBrowser templates from all locations in TEMPLATE_DIRS orcheck that these templates are compatible with the FileBrowser

Run the tests

Start the shell and type

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Check issues

If your setup is fine please check if your problem is a known issue

bull Take a look at all FileBrowser Issues (incuding closed) and search the FileBrowser Google-Group

Add a ticket

If you think yoursquove found a bug please add a ticket

bull Try to describe your problem as precisely as possible

bull Tell us what you did in order to solve the problem

bull Tell us what version of the FileBrowser you are using

bull Tell us what version of Django you are using

34 Chapter 6 Help

Django FileBrowser Documentation Release 357

bull Please do NOT add tickets if yoursquore having problems with serving staticmedia-files (because this is not relatedto the FileBrowser)

bull Please do NOT add tickets referring to Djangos trunk version

bull At best add a patch

Note Be aware that we may close issues not following these guidlines without further notifications

613 Translation

Translation is done via Transifex

Supported Languages

see httpswwwtransifexnetprojectspdjango-filebrowserresourcedjangopo

614 FileBrowser 35 Release Notes

FileBrowser 35 is compatible with Django 14151617 as well as Grappelli 242526

Update from FileBrowser 34x

bull Update Django to 14151617 and check httpsdocsdjangoprojectcomendevreleases14 orhttpsdocsdjangoprojectcomendevreleases15 or httpsdocsdjangoprojectcomendevreleases16

bull Update Grappelli to 24x25x26x

bull Update FileBrowser to 35x

62 Changelog

621 358 (not yet released)

622 357 (September 10th 2014)

bull New Compatibility with Django 17 and Grappelli 26x

bull Improved Updated tests because of the new random suffix with get_available_name (django storage)

bull Improved Added an icon in order to mark finished uploads

bull Improved Show resulting filename (eg with suffix converted) after successful upload

bull Fixed Permissions with file upload

bull Fixed Unified json response with _upload_file (no matter if file already exists or not)

623 356 (April 16th 2014)

bull Fixed Displaying pagination correctly with lots of entries

62 Changelog 35

Django FileBrowser Documentation Release 357

624 355 (April 13th 2014)

bull New Added client-side (JavaScript) file extension validation to the AJAX uploader

bull New Added experimental Python 33 support

bull Improved Tests with convertnormalize (removed special chars from test filename)

bull Fixed File selection after using search box (CKEditor)

bull Fixed Removed encoding of file URIs with CKEditor

625 354 (February 21st 2014)

bull Fixed Placeholder functionality (including tests)

bull Fixed Convertnormalize filenames (including tests)

bull Fixed Handling uppercase extensions with browse

626 353 (January 7 2014)

bull New added path_full to FileObject

bull Improved added docx to EXTENSIONS

bull Improved Recommend pillow instead of PIL as a requirement

bull Improved Added additional test cases

bull Improved Updated documentation

bull Improved Consistent use of storage (eg storagelocation storageurl)

bull Improved Removed unnecessary functions (eg url_join url_strip)

bull Improved Moved sort_by_attr to FileListing

bull Improved Regex matches with file versions on browse

bull Improved Using djangoconfurls (with djangoconfurlsdefaults as fallback)

bull Improved Adding CONTRIBUTINGrst

bull Improved Removed static Media inner class with fields

bull Improved Removed search icon with fields (has not being used)

bull Improved Added custom class attributes with filebrowser field

bull Improved Updated translations

bull Fixed fixed exception handling with python 25

bull Fixed fixes dir with SEARCH_TRAVERSE true and version select

bull Fixed Make Django FileUploadHandlers work (also fixed a memory leak)

bull Fixed return correct filename with OVERWRITE_EXISTING

bull Fixed fb_version_generate with FILEBROWSER_VERSIONS_BASEDIR

bull Fixed Table sorting with ascdesc

bull Fixed Added DeprecationWarning for FileObjectdirectory and FileObjectfolder

36 Chapter 6 Help

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

Django FileBrowser Documentation Release 357

gtgtgt fileobjectis_versionFalsegtgtgt versionis_versionTrue

versions_basedirThe relative path (from storage location) to the main versions folder Either VERSIONS_BASEDIR orsitedirectory

gtgtgt fileobjectversions_basedir_versionsgtgtgt versionversions_basedir_versions

originalReturns the original FileObject

gtgtgt fileobjectoriginalltFileObject uploadstestfoldertestimagejpggtgtgtgt versionoriginalltFileObject uploadstestfoldertestimagejpggt

original_filenameGet the filename of an original image from a version

gtgtgt fileobjectoriginal_filenametestimagejpggtgtgt versionoriginal_filenametestimagejpg

Methods

Version methods

versions()List all filenames based on VERSIONS

gtgtgt fileobjectversions()[_versionstestfoldertestimage_admin_thumbnailjpg_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionversions()[]

Note The versions are not being generated

admin_versions()List all filenames based on ADMIN_VERSIONS

gtgtgt fileobjectadmin_versions()[_versionstestfoldertestimage_thumbnailjpg_versionstestfoldertestimage_smalljpg_versionstestfoldertestimage_mediumjpg

21 API 17

Django FileBrowser Documentation Release 357

_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionadmin_versions()[]

Note The versions are not being generated

version_name(version_suffix)Get the filename for a version

gtgtgt fileobjectversion_name(medium)testimage_mediumjpg

Note The version is not being generated

version_path(version_suffix)Get the path for a version

gtgtgt fileobjectversion_path(medium)_versionstestfoldertestimage_mediumjpg

Note The version is not being generated

version_generate(version_suffix)Generate a version

gtgtgt fileobjectversion_generate(medium)ltFileObject uploadstestfoldertestimage_mediumjpggt

Please note that a version is only generated if it does not already exist or if the original image is newer than theexisting version

Delete methods

delete()Delete the File or Folder from the server

Warning If you delete a Folder all items within the folder are being deleted

delete_versions()Delete all VERSIONS

delete_admin_versions()Delete all ADMIN_VERSIONS

18 Chapter 2 API

CHAPTER 3

Fields amp Widgets

31 Fields amp Widgets

The FileBrowseField is a custom model field which returns a FileObject The widgets FileInput and ClearableFileIn-put are used with the admin app in order to show an additional thumbnail for images

311 FileBrowseField

class FileBrowseField(max_length[ site directory extensions format options])A subclass of CharField referencing a media file within Returns a FileObject

Parameters

bull site ndash A FileBrowser site (defaults to the main site) see FileBrowser Site

bull directory ndash Directory to browse when clicking the search icon

bull extensions ndash List of allowed extensions see Extensions and Formats

bull format ndash A key from SELECT_FORMATS in order to restrict the selection to specificfiletypes see Extensions and Formats

For example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 directory=images extensions=[jpg] blank=True null=True)document = FileBrowseField(PDF max_length=200 directory=documents extensions=[pdfdoc] blank=True null=True)

FileBrowseField in Templates

You can use all attributes from FileObject

blogentryimage ltimg src= publicationimageurl gt

ifequal blogentryimageimage_orientation landscape ltimg src= blogentryimageurl class=landscape gt

endifequal

19

Django FileBrowser Documentation Release 357

Showing Thumbnail in the Changelist

To show a thumbnail with the changelist you can define a ModelAdmin method

from filebrowsersettings import ADMIN_THUMBNAIL

def image_thumbnail(self obj)if objimage and objimagefiletype == Image

return ltimg src=s gt objimageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Using the FileBrowseField with TinyMCE

In order to replace the TinyMCE imagefile manager with the FileBrowser you have to use a FileBrowser CallbackTherersquos an example TinyMCE configuration file in staticjs called TinyMCEAdminjs You can either copy theFileBrowserCallback to your own file or just use tinymce_setupjs (which comes with django-grappelli)

Just add these lines to your ModelAdmin asset definitions

class Mediajs = [pathtotinymcejscriptstiny_mcetiny_mcejs

pathtoyourtinymce_setupjs]

312 FileInput

Subclass of FileInput with an additional thumbnail

from filebrowserwidgets import FileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget FileInput

313 ClearableFileInput

Subclass of ClearableFileInput with an additional thumbnail

from filebrowserwidgets import ClearableFileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget ClearableFileInput

314 Django FileField and the FileBrowser

Return a FileObject from a FileField or ImageField with

20 Chapter 3 Fields amp Widgets

Django FileBrowser Documentation Release 357

from filebrowserbase import FileObject

image_upload = modelsImageField(uImage (Upload) max_length=250 upload_to=image_upload_path blank=True null=True)

def image(self)if selfimage_upload

return FileObject(selfimage_uploadpath)return None

In order show a thumbnail with your changelist you could use a ModelAdmin method

from filebrowserbase import FileObject

def image_thumbnail(self obj)if objimage_upload

image = FileObject(objimage_uploadpath)if imagefiletype == Image

return ltimg src=s gt imageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Note There are different ways to achieve this The above examples show one of several options

31 Fields amp Widgets 21

Django FileBrowser Documentation Release 357

22 Chapter 3 Fields amp Widgets

CHAPTER 4

Admin Interface

41 Admin Interface

The main FileBrowser admin application is an extension for the Django admin interface in order to browser yourmedia folder upload and renamedelete files

411 FileBrowser Site

New in version 340

class FileBrowserSite(name=None app_name=rsquofilebrowserrsquo storage=default_storage)Respresents the FileBrowser admin application (similar to Djangorsquos admin site)

Parameters

bull name ndash A name for the site defaults to None

bull app_name ndash Defaults to lsquofilebrowserrsquo

bull storage ndash A custom storage engine defaults to Djangos default storage

Similar to djangocontribadmin you first need to add a filebrowsersite to your admin interface Inyour urlspy import the default FileBrowser site (or your custom site) and add the site to your URL-patterns (beforeany admin-urls)

from filebrowsersites import site

urlpatterns = patterns(url(r^adminurlfilebrowser include(siteurls))

)

Now you are able to browse the location defined with the storage engine associated to your site

from djangocorefilesstorage import DefaultStoragefrom filebrowsersites import FileBrowserSite

Default FileBrowser sitesite = FileBrowserSite(name=filebrowser storage=DefaultStorage())

My Custom FileBrowser sitecustom_site = FileBrowserSite(name=custom_filebrowser storage=DefaultStorage())custom_sitedirectory = custom_uploads

23

Django FileBrowser Documentation Release 357

Note The module variable site from filebrowsersites is the default FileBrowser application

412 Custom Actions

New in version 340

Similar to Djangorsquos admin actions you can define your FileBrowser actions and thus automate the typical tasks ofyour users Registered custom actions are listed in the detail view of a file and a user can select a single action at atime The selected action will then be applied to the file

The default FileBrowser image actions such as ldquoFlip Verticalrdquo or ldquoRotate 90deg Clockwiserdquo are in fact implemented ascustom actions (see the module filebrowseractions)

Writing Your Own Actions

Custom actions are simple functions

def foo(request fileobjects) Do something with the fileobjects

The first parameter is a HttpRequest object (representing the submitted form in which a user selected the action)and the second parameter is a list of FileObjects to which the action should be applied

The list contains exactly one instance of FileObject (representing the file from the detail view) but this may change inthe future as custom actions may become available also in browse views (similar to admin actions applied to a list ofchecked objects)

Registering an Action

In order to make your action visible you need to register it with a FileBrowser site

siteadd_action(foo)

Once registered the action will appear in the detail view of a file You can also give your action a short description

fooshort_description = Do foo with the File

This short description will then appear in the list of available actions If you do not provide a short description thefunction name will be used instead and FileBrowser will replace any underscores in the function name with spaces

Associating Actions with Specific Files

Each custom action can be associated with a specific file type (eg images audio file etc) to which it applies In orderto do that you need to define a predicatefilter function which takes a single argument (FileObject) and returns Trueif your action is applicable to that FileObject Finally you need to register this filter function with your action

fooapplies_to(lambda fileobject fileobjectfiletype == Image)

In the above example foo will appear in the action list only for image files If you do not specify any filter functionfor your action FileBrowser considers the action as applicable to all files

24 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

Messages amp Intermediate Pages

You can provide a feedback to a user about a successful or failed execution of an action by using a message Forexample

from djangocontrib import messages

def desaturate_image(request fileobjects)for f in fileobjects

Desaturate the imagemessagesadd_message(request messagesSUCCESS _(Image s was desaturated) ffilename)

Some actions may require user confirmation (eg in order to prevent accidental and irreversible modification tofiles) In order to that follow the same pattern as with Djangorsquos admin action and return a HttpResponse objectfrom your action Good practice for intermediate pages is to implement a confirm view and have your action returnHttpResponseRedirect

def crop_image(request fileobjects)files = ampf=join([fpath_relative for f in fileobjects])return HttpResponseRedirect(confirmaction=crop_imageampf=s files)

413 File Storages

New in version 340

You have the option to specify which file storage engine a FileBrowser should use to browseuploadmodify yourmedia files This enables you to use a FileBrowser even if your media files are located at some remote system Seealso the Djangorsquos documentation on storages httpsdocsdjangoprojectcomendevtopicsfiles

To associate a FileBrowser site with a particular storage engine set the storage property of a site object

from djangocorefilesstorage import FileSystemStoragesitestorage = FileSystemStorage(location=pathtomediadirectory base_url=media)

For storage classes other than FileSystemStorage (or those that inherit from that class) therersquos more effort involved inproviding a storage object that can be used with FileBrowser See StorageMixin Class

Note Prior FileBrowser 34 the way to specify FileBrowserlsquos MEDIA_ROOT and MEDIA_URL was via settingspyStarting from version 34 those variables are associated with the storage instance and you can set them as illustratedin the above example

Warning For the reason of backward compatibility FileBrowser settings FILEBROWSER_MEDIA_ROOT andFILEBROWSER_MEDIA_URL can still be used to customize FileBrowser as long as yoursquore using the defaultFileBrowserlsquos site without having changed its storage engine In the next major release of FileBrowser thesesettings will be removed

StorageMixin Class

A FileBrowser uses the Djangorsquos Storage class to access media files However the API of the Storageclass does not provide all methods necessary for FileBrowserrsquos functionality A StorageMixin class fromfilebrowserstorage module therefore defines all the additional methods that a FileBrowser requires

isdir(self name)Returns true if name exists and is a directory

41 Admin Interface 25

Django FileBrowser Documentation Release 357

isfile(self name)Returns true if name exists and is a regular file

move(self old_file_name new_file_name allow_overwrite=False)Moves safely a file from one location to another If allow_ovewrite==False and new_file_nameexists raises an exception

makedirs(self name)Creates all missing directories specified by name Analogue to osmkdirs()

414 Views

All views use the staff_member_requird and path_exists decorator in order to check if the server pathactually exists Some views also use the file_exists decorator

bull Browse fb_browse Browse a directory on your server Returns a FileListing

ndash Optional query string args dir o ot q p filter_date filter_type type

bull Create directory fb_createdir Create a new folder on your server

ndash Optional query string args dir

ndash Signals filebrowser_pre_createdir filebrowser_post_createdir

bull Upload fb_upload Multiple upload

ndash Optional query string args dir type

ndash Signals filebrowser_pre_upload filebrowser_post_upload

bull Edit fb_edit Edit a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_rename filebrowser_post_rename

You are able to apply custom actions (see Custom Actions) to the edit-view

bull Confirm delete fb_confirm_delete Confirm the deletion of a file or folder

ndash Required query string args filename

ndash Optional query string args dir

If you try to delete a folder all filesfolders within this folder are listed on this page

bull Delete fb_delete Delete a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_delete filebrowser_post_delete

Warning If you delete a Folder all items within this Folder are being deleted

bull Version fb_version Generate a version of an image as defined with ADMIN_VERSIONS

ndash Required query string args filename

ndash Optional Query string args dir

This is a helper used by the FileBrowseField and TinyMCE for selecting a version

26 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

415 Signals

The FileBrowser sends a couple of different signals Please take a look at the module filebrowsersignals for furtherexplanation on the provided arguments

bull filebrowser_pre_upload Sent before a an Upload starts

bull filebrowser_post_upload Sent after an Upload has finished

bull filebrowser_pre_delete Sent before an Item (File Folder) is deleted

bull filebrowser_post_delete Sent after an Item (File Folder) has been deleted

bull filebrowser_pre_createdir Sent before a new Folder is created

bull filebrowser_post_createdir Sent after a new Folder has been created

bull filebrowser_pre_rename Sent before an Item (File Folder) is renamed

bull filebrowser_post_rename Sent after an Item (File Folder) has been renamed

bull filebrowser_actions_pre_apply Sent before a custom action is applied

bull filebrowser_actions_post_apply Sent after a custom action has been applied

Example for using these Signals

Herersquos a small example for using the above Signals

from filebrowser import signals

def pre_upload_callback(sender kwargs)Receiver function called before an upload startsprint Pre Upload Callbackprint kwargs kwargs

signalsfilebrowser_pre_uploadconnect(pre_upload_callback)

def post_upload_callback(sender kwargs)Receiver function called each time an upload has finishedprint Post Upload Callbackprint kwargs kwargs You can use all attributes available with the FileObject This is just an example print Filesize kwargs[file]filesizeprint Orientation kwargs[file]orientationprint Extension kwargs[file]extension

signalsfilebrowser_post_uploadconnect(post_upload_callback)

41 Admin Interface 27

Django FileBrowser Documentation Release 357

28 Chapter 4 Admin Interface

CHAPTER 5

Image Versions

51 Versions

With the FileBrowser you are able to define different versionssizes for images This enables you to save an originalimage on your server while having different versions of that image to automatically fit your websites grid Versionsare also useful for responsiveadaptive layouts

511 Defining Versions

New in version 340 methods

First you need to know which versionssizes of an image yoursquod like to generate with your website Letrsquos say yoursquoreusing a 12 column grid with 60px for each column and 20px margin (which is a total of 940px) With this grid youcould (for example) define these image versions

FILEBROWSER_VERSIONS_BASEDIR = _versionsFILEBROWSER_VERSIONS =

admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

Use the methods argument if you need to add a filter

def grayscale(im)Convert image to grayscaleif immode = L

im = imconvert(L)return im

FILEBROWSER_VERSIONS = big verbose_name Big (6 col) width 460 height opts methods [grayscale]

)

29

Django FileBrowser Documentation Release 357

512 Versions and the Admin

When using the FileBrowser with the admin interface you need to define ADMIN_VERSIONS andADMIN_THUMBNAIL (see Settings) ADMIN_VERSIONS are available with the admin ie you are able to seethese versions with the image detail view and you are able to select the versions with the FileBrowseField model field

FILEBROWSER_ADMIN_VERSIONS = [thumbnail small medium big large]FILEBROWSER_ADMIN_THUMBNAIL = admin_thumbnail

513 Versions and the Frontend

With your templates you have two different tags to choose from version and version_object With bothtags the version will be generated if it doesnrsquot already exist OR if the original image is newer than the version Inorder to update an image you just overwrite the original image and the versions will be generated automatically (asyou request them within your template)

A Model example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 blank=True null=True)

With your templates use version if you simply need to retrieve the URL or version_object if you need to geta FileObject

lt-- load filebrowser templatetags --gt load fb_versions

lt-- get the url with version --gtltimg src= version blogentryimage medium gt

lt-- get a fileobject with version_object --gt version_object blogentryimage medium as version_medium version_mediumwidth ltimg src= version_medium gt

Templatetag version

RetrievesGenerates a version and returns an URL

version modelfield_name version_prefix

Templatetag version_object

RetrievesGenerates a version and returns a FileObject

version_object modelfield_name version_prefix as variable

Note With both templatetags version_prefix can either be a string or a variable If version_prefix is astring use quotes

30 Chapter 5 Image Versions

Django FileBrowser Documentation Release 357

514 Versions in Views

If you have a FileObject you can generateretrieve a version with

v = objimageversion_generate(version_prefix) returns a FileObject

515 Placeholder

When developing on a locale machine or a development-server you might not have all the images (resp media-files)available that are on your production instance and downloading these files on a regular basis might not be an option

In that case you can use a placeholder instead of a version You just need to define the PLACEHOLDER and overwritethe settings SHOW_PLACEHOLDER andor FORCE_PLACEHOLDER (see Placeholder)

516 Management Commands

fb_version_generateIf you need to generate certain (or all) versions type

python managepy fb_version_generate

fb_version_removeIf you need to generate certain (or all) versions type

python managepy fb_version_generate

Warning Please be very careful with this command

51 Versions 31

Django FileBrowser Documentation Release 357

32 Chapter 5 Image Versions

CHAPTER 6

Help

61 Help

611 FAQ

Why should I use the FileBrowser

If you need your editors or customers to manage files the FileBrowser is an alternative to an FTP-client Moreoveryou are able to define different image versions according to your websites grid Alternatives to the FileBrowser can befound at httpdjangopackagescomgridsgfile-managers

Do I need Grappelli

Grappelli is a requirement for using the FileBrowser There are several filebrowser-no-grappelli repositories (most ofthem on GitHub) but we donrsquot follow the development

I need help

see Troubleshooting

Why are there no fancy effects

The FileBrowser is about managing files We think that you should prepare your files before uploading them to theserver

How do I upload to another server

Use a custom storage engine see httpsdocsdjangoprojectcomen16howtocustom-file-storage

Why do I need image-versions

You need image-versions if your website is based on a grid

33

Django FileBrowser Documentation Release 357

Is the FileBrowser stable

Wersquove developed the FileBrowser for a couple of years and use it with almost all of our clients That said Grappelli isthe more stable and mature application

How can I contribute

Help is very much needed and appreciated Test the FileBrowser and submit feedbackpatches

Who develops the FileBrowser

The FileBrowser is developed and maintained by Patrick Kranzlmuumlller amp Axel Swoboda of vonautomatisch

612 Troubleshooting

Check your setup

Please check if the problem is caused by your setup

bull Read Quick start guide

bull Check if the staticmedia-files are served correctly

bull Make sure you have removed all custom FileBrowser templates from all locations in TEMPLATE_DIRS orcheck that these templates are compatible with the FileBrowser

Run the tests

Start the shell and type

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Check issues

If your setup is fine please check if your problem is a known issue

bull Take a look at all FileBrowser Issues (incuding closed) and search the FileBrowser Google-Group

Add a ticket

If you think yoursquove found a bug please add a ticket

bull Try to describe your problem as precisely as possible

bull Tell us what you did in order to solve the problem

bull Tell us what version of the FileBrowser you are using

bull Tell us what version of Django you are using

34 Chapter 6 Help

Django FileBrowser Documentation Release 357

bull Please do NOT add tickets if yoursquore having problems with serving staticmedia-files (because this is not relatedto the FileBrowser)

bull Please do NOT add tickets referring to Djangos trunk version

bull At best add a patch

Note Be aware that we may close issues not following these guidlines without further notifications

613 Translation

Translation is done via Transifex

Supported Languages

see httpswwwtransifexnetprojectspdjango-filebrowserresourcedjangopo

614 FileBrowser 35 Release Notes

FileBrowser 35 is compatible with Django 14151617 as well as Grappelli 242526

Update from FileBrowser 34x

bull Update Django to 14151617 and check httpsdocsdjangoprojectcomendevreleases14 orhttpsdocsdjangoprojectcomendevreleases15 or httpsdocsdjangoprojectcomendevreleases16

bull Update Grappelli to 24x25x26x

bull Update FileBrowser to 35x

62 Changelog

621 358 (not yet released)

622 357 (September 10th 2014)

bull New Compatibility with Django 17 and Grappelli 26x

bull Improved Updated tests because of the new random suffix with get_available_name (django storage)

bull Improved Added an icon in order to mark finished uploads

bull Improved Show resulting filename (eg with suffix converted) after successful upload

bull Fixed Permissions with file upload

bull Fixed Unified json response with _upload_file (no matter if file already exists or not)

623 356 (April 16th 2014)

bull Fixed Displaying pagination correctly with lots of entries

62 Changelog 35

Django FileBrowser Documentation Release 357

624 355 (April 13th 2014)

bull New Added client-side (JavaScript) file extension validation to the AJAX uploader

bull New Added experimental Python 33 support

bull Improved Tests with convertnormalize (removed special chars from test filename)

bull Fixed File selection after using search box (CKEditor)

bull Fixed Removed encoding of file URIs with CKEditor

625 354 (February 21st 2014)

bull Fixed Placeholder functionality (including tests)

bull Fixed Convertnormalize filenames (including tests)

bull Fixed Handling uppercase extensions with browse

626 353 (January 7 2014)

bull New added path_full to FileObject

bull Improved added docx to EXTENSIONS

bull Improved Recommend pillow instead of PIL as a requirement

bull Improved Added additional test cases

bull Improved Updated documentation

bull Improved Consistent use of storage (eg storagelocation storageurl)

bull Improved Removed unnecessary functions (eg url_join url_strip)

bull Improved Moved sort_by_attr to FileListing

bull Improved Regex matches with file versions on browse

bull Improved Using djangoconfurls (with djangoconfurlsdefaults as fallback)

bull Improved Adding CONTRIBUTINGrst

bull Improved Removed static Media inner class with fields

bull Improved Removed search icon with fields (has not being used)

bull Improved Added custom class attributes with filebrowser field

bull Improved Updated translations

bull Fixed fixed exception handling with python 25

bull Fixed fixes dir with SEARCH_TRAVERSE true and version select

bull Fixed Make Django FileUploadHandlers work (also fixed a memory leak)

bull Fixed return correct filename with OVERWRITE_EXISTING

bull Fixed fb_version_generate with FILEBROWSER_VERSIONS_BASEDIR

bull Fixed Table sorting with ascdesc

bull Fixed Added DeprecationWarning for FileObjectdirectory and FileObjectfolder

36 Chapter 6 Help

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

Django FileBrowser Documentation Release 357

_versionstestfoldertestimage_bigjpg_versionstestfoldertestimage_largejpg]gtgtgt versionadmin_versions()[]

Note The versions are not being generated

version_name(version_suffix)Get the filename for a version

gtgtgt fileobjectversion_name(medium)testimage_mediumjpg

Note The version is not being generated

version_path(version_suffix)Get the path for a version

gtgtgt fileobjectversion_path(medium)_versionstestfoldertestimage_mediumjpg

Note The version is not being generated

version_generate(version_suffix)Generate a version

gtgtgt fileobjectversion_generate(medium)ltFileObject uploadstestfoldertestimage_mediumjpggt

Please note that a version is only generated if it does not already exist or if the original image is newer than theexisting version

Delete methods

delete()Delete the File or Folder from the server

Warning If you delete a Folder all items within the folder are being deleted

delete_versions()Delete all VERSIONS

delete_admin_versions()Delete all ADMIN_VERSIONS

18 Chapter 2 API

CHAPTER 3

Fields amp Widgets

31 Fields amp Widgets

The FileBrowseField is a custom model field which returns a FileObject The widgets FileInput and ClearableFileIn-put are used with the admin app in order to show an additional thumbnail for images

311 FileBrowseField

class FileBrowseField(max_length[ site directory extensions format options])A subclass of CharField referencing a media file within Returns a FileObject

Parameters

bull site ndash A FileBrowser site (defaults to the main site) see FileBrowser Site

bull directory ndash Directory to browse when clicking the search icon

bull extensions ndash List of allowed extensions see Extensions and Formats

bull format ndash A key from SELECT_FORMATS in order to restrict the selection to specificfiletypes see Extensions and Formats

For example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 directory=images extensions=[jpg] blank=True null=True)document = FileBrowseField(PDF max_length=200 directory=documents extensions=[pdfdoc] blank=True null=True)

FileBrowseField in Templates

You can use all attributes from FileObject

blogentryimage ltimg src= publicationimageurl gt

ifequal blogentryimageimage_orientation landscape ltimg src= blogentryimageurl class=landscape gt

endifequal

19

Django FileBrowser Documentation Release 357

Showing Thumbnail in the Changelist

To show a thumbnail with the changelist you can define a ModelAdmin method

from filebrowsersettings import ADMIN_THUMBNAIL

def image_thumbnail(self obj)if objimage and objimagefiletype == Image

return ltimg src=s gt objimageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Using the FileBrowseField with TinyMCE

In order to replace the TinyMCE imagefile manager with the FileBrowser you have to use a FileBrowser CallbackTherersquos an example TinyMCE configuration file in staticjs called TinyMCEAdminjs You can either copy theFileBrowserCallback to your own file or just use tinymce_setupjs (which comes with django-grappelli)

Just add these lines to your ModelAdmin asset definitions

class Mediajs = [pathtotinymcejscriptstiny_mcetiny_mcejs

pathtoyourtinymce_setupjs]

312 FileInput

Subclass of FileInput with an additional thumbnail

from filebrowserwidgets import FileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget FileInput

313 ClearableFileInput

Subclass of ClearableFileInput with an additional thumbnail

from filebrowserwidgets import ClearableFileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget ClearableFileInput

314 Django FileField and the FileBrowser

Return a FileObject from a FileField or ImageField with

20 Chapter 3 Fields amp Widgets

Django FileBrowser Documentation Release 357

from filebrowserbase import FileObject

image_upload = modelsImageField(uImage (Upload) max_length=250 upload_to=image_upload_path blank=True null=True)

def image(self)if selfimage_upload

return FileObject(selfimage_uploadpath)return None

In order show a thumbnail with your changelist you could use a ModelAdmin method

from filebrowserbase import FileObject

def image_thumbnail(self obj)if objimage_upload

image = FileObject(objimage_uploadpath)if imagefiletype == Image

return ltimg src=s gt imageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Note There are different ways to achieve this The above examples show one of several options

31 Fields amp Widgets 21

Django FileBrowser Documentation Release 357

22 Chapter 3 Fields amp Widgets

CHAPTER 4

Admin Interface

41 Admin Interface

The main FileBrowser admin application is an extension for the Django admin interface in order to browser yourmedia folder upload and renamedelete files

411 FileBrowser Site

New in version 340

class FileBrowserSite(name=None app_name=rsquofilebrowserrsquo storage=default_storage)Respresents the FileBrowser admin application (similar to Djangorsquos admin site)

Parameters

bull name ndash A name for the site defaults to None

bull app_name ndash Defaults to lsquofilebrowserrsquo

bull storage ndash A custom storage engine defaults to Djangos default storage

Similar to djangocontribadmin you first need to add a filebrowsersite to your admin interface Inyour urlspy import the default FileBrowser site (or your custom site) and add the site to your URL-patterns (beforeany admin-urls)

from filebrowsersites import site

urlpatterns = patterns(url(r^adminurlfilebrowser include(siteurls))

)

Now you are able to browse the location defined with the storage engine associated to your site

from djangocorefilesstorage import DefaultStoragefrom filebrowsersites import FileBrowserSite

Default FileBrowser sitesite = FileBrowserSite(name=filebrowser storage=DefaultStorage())

My Custom FileBrowser sitecustom_site = FileBrowserSite(name=custom_filebrowser storage=DefaultStorage())custom_sitedirectory = custom_uploads

23

Django FileBrowser Documentation Release 357

Note The module variable site from filebrowsersites is the default FileBrowser application

412 Custom Actions

New in version 340

Similar to Djangorsquos admin actions you can define your FileBrowser actions and thus automate the typical tasks ofyour users Registered custom actions are listed in the detail view of a file and a user can select a single action at atime The selected action will then be applied to the file

The default FileBrowser image actions such as ldquoFlip Verticalrdquo or ldquoRotate 90deg Clockwiserdquo are in fact implemented ascustom actions (see the module filebrowseractions)

Writing Your Own Actions

Custom actions are simple functions

def foo(request fileobjects) Do something with the fileobjects

The first parameter is a HttpRequest object (representing the submitted form in which a user selected the action)and the second parameter is a list of FileObjects to which the action should be applied

The list contains exactly one instance of FileObject (representing the file from the detail view) but this may change inthe future as custom actions may become available also in browse views (similar to admin actions applied to a list ofchecked objects)

Registering an Action

In order to make your action visible you need to register it with a FileBrowser site

siteadd_action(foo)

Once registered the action will appear in the detail view of a file You can also give your action a short description

fooshort_description = Do foo with the File

This short description will then appear in the list of available actions If you do not provide a short description thefunction name will be used instead and FileBrowser will replace any underscores in the function name with spaces

Associating Actions with Specific Files

Each custom action can be associated with a specific file type (eg images audio file etc) to which it applies In orderto do that you need to define a predicatefilter function which takes a single argument (FileObject) and returns Trueif your action is applicable to that FileObject Finally you need to register this filter function with your action

fooapplies_to(lambda fileobject fileobjectfiletype == Image)

In the above example foo will appear in the action list only for image files If you do not specify any filter functionfor your action FileBrowser considers the action as applicable to all files

24 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

Messages amp Intermediate Pages

You can provide a feedback to a user about a successful or failed execution of an action by using a message Forexample

from djangocontrib import messages

def desaturate_image(request fileobjects)for f in fileobjects

Desaturate the imagemessagesadd_message(request messagesSUCCESS _(Image s was desaturated) ffilename)

Some actions may require user confirmation (eg in order to prevent accidental and irreversible modification tofiles) In order to that follow the same pattern as with Djangorsquos admin action and return a HttpResponse objectfrom your action Good practice for intermediate pages is to implement a confirm view and have your action returnHttpResponseRedirect

def crop_image(request fileobjects)files = ampf=join([fpath_relative for f in fileobjects])return HttpResponseRedirect(confirmaction=crop_imageampf=s files)

413 File Storages

New in version 340

You have the option to specify which file storage engine a FileBrowser should use to browseuploadmodify yourmedia files This enables you to use a FileBrowser even if your media files are located at some remote system Seealso the Djangorsquos documentation on storages httpsdocsdjangoprojectcomendevtopicsfiles

To associate a FileBrowser site with a particular storage engine set the storage property of a site object

from djangocorefilesstorage import FileSystemStoragesitestorage = FileSystemStorage(location=pathtomediadirectory base_url=media)

For storage classes other than FileSystemStorage (or those that inherit from that class) therersquos more effort involved inproviding a storage object that can be used with FileBrowser See StorageMixin Class

Note Prior FileBrowser 34 the way to specify FileBrowserlsquos MEDIA_ROOT and MEDIA_URL was via settingspyStarting from version 34 those variables are associated with the storage instance and you can set them as illustratedin the above example

Warning For the reason of backward compatibility FileBrowser settings FILEBROWSER_MEDIA_ROOT andFILEBROWSER_MEDIA_URL can still be used to customize FileBrowser as long as yoursquore using the defaultFileBrowserlsquos site without having changed its storage engine In the next major release of FileBrowser thesesettings will be removed

StorageMixin Class

A FileBrowser uses the Djangorsquos Storage class to access media files However the API of the Storageclass does not provide all methods necessary for FileBrowserrsquos functionality A StorageMixin class fromfilebrowserstorage module therefore defines all the additional methods that a FileBrowser requires

isdir(self name)Returns true if name exists and is a directory

41 Admin Interface 25

Django FileBrowser Documentation Release 357

isfile(self name)Returns true if name exists and is a regular file

move(self old_file_name new_file_name allow_overwrite=False)Moves safely a file from one location to another If allow_ovewrite==False and new_file_nameexists raises an exception

makedirs(self name)Creates all missing directories specified by name Analogue to osmkdirs()

414 Views

All views use the staff_member_requird and path_exists decorator in order to check if the server pathactually exists Some views also use the file_exists decorator

bull Browse fb_browse Browse a directory on your server Returns a FileListing

ndash Optional query string args dir o ot q p filter_date filter_type type

bull Create directory fb_createdir Create a new folder on your server

ndash Optional query string args dir

ndash Signals filebrowser_pre_createdir filebrowser_post_createdir

bull Upload fb_upload Multiple upload

ndash Optional query string args dir type

ndash Signals filebrowser_pre_upload filebrowser_post_upload

bull Edit fb_edit Edit a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_rename filebrowser_post_rename

You are able to apply custom actions (see Custom Actions) to the edit-view

bull Confirm delete fb_confirm_delete Confirm the deletion of a file or folder

ndash Required query string args filename

ndash Optional query string args dir

If you try to delete a folder all filesfolders within this folder are listed on this page

bull Delete fb_delete Delete a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_delete filebrowser_post_delete

Warning If you delete a Folder all items within this Folder are being deleted

bull Version fb_version Generate a version of an image as defined with ADMIN_VERSIONS

ndash Required query string args filename

ndash Optional Query string args dir

This is a helper used by the FileBrowseField and TinyMCE for selecting a version

26 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

415 Signals

The FileBrowser sends a couple of different signals Please take a look at the module filebrowsersignals for furtherexplanation on the provided arguments

bull filebrowser_pre_upload Sent before a an Upload starts

bull filebrowser_post_upload Sent after an Upload has finished

bull filebrowser_pre_delete Sent before an Item (File Folder) is deleted

bull filebrowser_post_delete Sent after an Item (File Folder) has been deleted

bull filebrowser_pre_createdir Sent before a new Folder is created

bull filebrowser_post_createdir Sent after a new Folder has been created

bull filebrowser_pre_rename Sent before an Item (File Folder) is renamed

bull filebrowser_post_rename Sent after an Item (File Folder) has been renamed

bull filebrowser_actions_pre_apply Sent before a custom action is applied

bull filebrowser_actions_post_apply Sent after a custom action has been applied

Example for using these Signals

Herersquos a small example for using the above Signals

from filebrowser import signals

def pre_upload_callback(sender kwargs)Receiver function called before an upload startsprint Pre Upload Callbackprint kwargs kwargs

signalsfilebrowser_pre_uploadconnect(pre_upload_callback)

def post_upload_callback(sender kwargs)Receiver function called each time an upload has finishedprint Post Upload Callbackprint kwargs kwargs You can use all attributes available with the FileObject This is just an example print Filesize kwargs[file]filesizeprint Orientation kwargs[file]orientationprint Extension kwargs[file]extension

signalsfilebrowser_post_uploadconnect(post_upload_callback)

41 Admin Interface 27

Django FileBrowser Documentation Release 357

28 Chapter 4 Admin Interface

CHAPTER 5

Image Versions

51 Versions

With the FileBrowser you are able to define different versionssizes for images This enables you to save an originalimage on your server while having different versions of that image to automatically fit your websites grid Versionsare also useful for responsiveadaptive layouts

511 Defining Versions

New in version 340 methods

First you need to know which versionssizes of an image yoursquod like to generate with your website Letrsquos say yoursquoreusing a 12 column grid with 60px for each column and 20px margin (which is a total of 940px) With this grid youcould (for example) define these image versions

FILEBROWSER_VERSIONS_BASEDIR = _versionsFILEBROWSER_VERSIONS =

admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

Use the methods argument if you need to add a filter

def grayscale(im)Convert image to grayscaleif immode = L

im = imconvert(L)return im

FILEBROWSER_VERSIONS = big verbose_name Big (6 col) width 460 height opts methods [grayscale]

)

29

Django FileBrowser Documentation Release 357

512 Versions and the Admin

When using the FileBrowser with the admin interface you need to define ADMIN_VERSIONS andADMIN_THUMBNAIL (see Settings) ADMIN_VERSIONS are available with the admin ie you are able to seethese versions with the image detail view and you are able to select the versions with the FileBrowseField model field

FILEBROWSER_ADMIN_VERSIONS = [thumbnail small medium big large]FILEBROWSER_ADMIN_THUMBNAIL = admin_thumbnail

513 Versions and the Frontend

With your templates you have two different tags to choose from version and version_object With bothtags the version will be generated if it doesnrsquot already exist OR if the original image is newer than the version Inorder to update an image you just overwrite the original image and the versions will be generated automatically (asyou request them within your template)

A Model example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 blank=True null=True)

With your templates use version if you simply need to retrieve the URL or version_object if you need to geta FileObject

lt-- load filebrowser templatetags --gt load fb_versions

lt-- get the url with version --gtltimg src= version blogentryimage medium gt

lt-- get a fileobject with version_object --gt version_object blogentryimage medium as version_medium version_mediumwidth ltimg src= version_medium gt

Templatetag version

RetrievesGenerates a version and returns an URL

version modelfield_name version_prefix

Templatetag version_object

RetrievesGenerates a version and returns a FileObject

version_object modelfield_name version_prefix as variable

Note With both templatetags version_prefix can either be a string or a variable If version_prefix is astring use quotes

30 Chapter 5 Image Versions

Django FileBrowser Documentation Release 357

514 Versions in Views

If you have a FileObject you can generateretrieve a version with

v = objimageversion_generate(version_prefix) returns a FileObject

515 Placeholder

When developing on a locale machine or a development-server you might not have all the images (resp media-files)available that are on your production instance and downloading these files on a regular basis might not be an option

In that case you can use a placeholder instead of a version You just need to define the PLACEHOLDER and overwritethe settings SHOW_PLACEHOLDER andor FORCE_PLACEHOLDER (see Placeholder)

516 Management Commands

fb_version_generateIf you need to generate certain (or all) versions type

python managepy fb_version_generate

fb_version_removeIf you need to generate certain (or all) versions type

python managepy fb_version_generate

Warning Please be very careful with this command

51 Versions 31

Django FileBrowser Documentation Release 357

32 Chapter 5 Image Versions

CHAPTER 6

Help

61 Help

611 FAQ

Why should I use the FileBrowser

If you need your editors or customers to manage files the FileBrowser is an alternative to an FTP-client Moreoveryou are able to define different image versions according to your websites grid Alternatives to the FileBrowser can befound at httpdjangopackagescomgridsgfile-managers

Do I need Grappelli

Grappelli is a requirement for using the FileBrowser There are several filebrowser-no-grappelli repositories (most ofthem on GitHub) but we donrsquot follow the development

I need help

see Troubleshooting

Why are there no fancy effects

The FileBrowser is about managing files We think that you should prepare your files before uploading them to theserver

How do I upload to another server

Use a custom storage engine see httpsdocsdjangoprojectcomen16howtocustom-file-storage

Why do I need image-versions

You need image-versions if your website is based on a grid

33

Django FileBrowser Documentation Release 357

Is the FileBrowser stable

Wersquove developed the FileBrowser for a couple of years and use it with almost all of our clients That said Grappelli isthe more stable and mature application

How can I contribute

Help is very much needed and appreciated Test the FileBrowser and submit feedbackpatches

Who develops the FileBrowser

The FileBrowser is developed and maintained by Patrick Kranzlmuumlller amp Axel Swoboda of vonautomatisch

612 Troubleshooting

Check your setup

Please check if the problem is caused by your setup

bull Read Quick start guide

bull Check if the staticmedia-files are served correctly

bull Make sure you have removed all custom FileBrowser templates from all locations in TEMPLATE_DIRS orcheck that these templates are compatible with the FileBrowser

Run the tests

Start the shell and type

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Check issues

If your setup is fine please check if your problem is a known issue

bull Take a look at all FileBrowser Issues (incuding closed) and search the FileBrowser Google-Group

Add a ticket

If you think yoursquove found a bug please add a ticket

bull Try to describe your problem as precisely as possible

bull Tell us what you did in order to solve the problem

bull Tell us what version of the FileBrowser you are using

bull Tell us what version of Django you are using

34 Chapter 6 Help

Django FileBrowser Documentation Release 357

bull Please do NOT add tickets if yoursquore having problems with serving staticmedia-files (because this is not relatedto the FileBrowser)

bull Please do NOT add tickets referring to Djangos trunk version

bull At best add a patch

Note Be aware that we may close issues not following these guidlines without further notifications

613 Translation

Translation is done via Transifex

Supported Languages

see httpswwwtransifexnetprojectspdjango-filebrowserresourcedjangopo

614 FileBrowser 35 Release Notes

FileBrowser 35 is compatible with Django 14151617 as well as Grappelli 242526

Update from FileBrowser 34x

bull Update Django to 14151617 and check httpsdocsdjangoprojectcomendevreleases14 orhttpsdocsdjangoprojectcomendevreleases15 or httpsdocsdjangoprojectcomendevreleases16

bull Update Grappelli to 24x25x26x

bull Update FileBrowser to 35x

62 Changelog

621 358 (not yet released)

622 357 (September 10th 2014)

bull New Compatibility with Django 17 and Grappelli 26x

bull Improved Updated tests because of the new random suffix with get_available_name (django storage)

bull Improved Added an icon in order to mark finished uploads

bull Improved Show resulting filename (eg with suffix converted) after successful upload

bull Fixed Permissions with file upload

bull Fixed Unified json response with _upload_file (no matter if file already exists or not)

623 356 (April 16th 2014)

bull Fixed Displaying pagination correctly with lots of entries

62 Changelog 35

Django FileBrowser Documentation Release 357

624 355 (April 13th 2014)

bull New Added client-side (JavaScript) file extension validation to the AJAX uploader

bull New Added experimental Python 33 support

bull Improved Tests with convertnormalize (removed special chars from test filename)

bull Fixed File selection after using search box (CKEditor)

bull Fixed Removed encoding of file URIs with CKEditor

625 354 (February 21st 2014)

bull Fixed Placeholder functionality (including tests)

bull Fixed Convertnormalize filenames (including tests)

bull Fixed Handling uppercase extensions with browse

626 353 (January 7 2014)

bull New added path_full to FileObject

bull Improved added docx to EXTENSIONS

bull Improved Recommend pillow instead of PIL as a requirement

bull Improved Added additional test cases

bull Improved Updated documentation

bull Improved Consistent use of storage (eg storagelocation storageurl)

bull Improved Removed unnecessary functions (eg url_join url_strip)

bull Improved Moved sort_by_attr to FileListing

bull Improved Regex matches with file versions on browse

bull Improved Using djangoconfurls (with djangoconfurlsdefaults as fallback)

bull Improved Adding CONTRIBUTINGrst

bull Improved Removed static Media inner class with fields

bull Improved Removed search icon with fields (has not being used)

bull Improved Added custom class attributes with filebrowser field

bull Improved Updated translations

bull Fixed fixed exception handling with python 25

bull Fixed fixes dir with SEARCH_TRAVERSE true and version select

bull Fixed Make Django FileUploadHandlers work (also fixed a memory leak)

bull Fixed return correct filename with OVERWRITE_EXISTING

bull Fixed fb_version_generate with FILEBROWSER_VERSIONS_BASEDIR

bull Fixed Table sorting with ascdesc

bull Fixed Added DeprecationWarning for FileObjectdirectory and FileObjectfolder

36 Chapter 6 Help

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

CHAPTER 3

Fields amp Widgets

31 Fields amp Widgets

The FileBrowseField is a custom model field which returns a FileObject The widgets FileInput and ClearableFileIn-put are used with the admin app in order to show an additional thumbnail for images

311 FileBrowseField

class FileBrowseField(max_length[ site directory extensions format options])A subclass of CharField referencing a media file within Returns a FileObject

Parameters

bull site ndash A FileBrowser site (defaults to the main site) see FileBrowser Site

bull directory ndash Directory to browse when clicking the search icon

bull extensions ndash List of allowed extensions see Extensions and Formats

bull format ndash A key from SELECT_FORMATS in order to restrict the selection to specificfiletypes see Extensions and Formats

For example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 directory=images extensions=[jpg] blank=True null=True)document = FileBrowseField(PDF max_length=200 directory=documents extensions=[pdfdoc] blank=True null=True)

FileBrowseField in Templates

You can use all attributes from FileObject

blogentryimage ltimg src= publicationimageurl gt

ifequal blogentryimageimage_orientation landscape ltimg src= blogentryimageurl class=landscape gt

endifequal

19

Django FileBrowser Documentation Release 357

Showing Thumbnail in the Changelist

To show a thumbnail with the changelist you can define a ModelAdmin method

from filebrowsersettings import ADMIN_THUMBNAIL

def image_thumbnail(self obj)if objimage and objimagefiletype == Image

return ltimg src=s gt objimageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Using the FileBrowseField with TinyMCE

In order to replace the TinyMCE imagefile manager with the FileBrowser you have to use a FileBrowser CallbackTherersquos an example TinyMCE configuration file in staticjs called TinyMCEAdminjs You can either copy theFileBrowserCallback to your own file or just use tinymce_setupjs (which comes with django-grappelli)

Just add these lines to your ModelAdmin asset definitions

class Mediajs = [pathtotinymcejscriptstiny_mcetiny_mcejs

pathtoyourtinymce_setupjs]

312 FileInput

Subclass of FileInput with an additional thumbnail

from filebrowserwidgets import FileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget FileInput

313 ClearableFileInput

Subclass of ClearableFileInput with an additional thumbnail

from filebrowserwidgets import ClearableFileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget ClearableFileInput

314 Django FileField and the FileBrowser

Return a FileObject from a FileField or ImageField with

20 Chapter 3 Fields amp Widgets

Django FileBrowser Documentation Release 357

from filebrowserbase import FileObject

image_upload = modelsImageField(uImage (Upload) max_length=250 upload_to=image_upload_path blank=True null=True)

def image(self)if selfimage_upload

return FileObject(selfimage_uploadpath)return None

In order show a thumbnail with your changelist you could use a ModelAdmin method

from filebrowserbase import FileObject

def image_thumbnail(self obj)if objimage_upload

image = FileObject(objimage_uploadpath)if imagefiletype == Image

return ltimg src=s gt imageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Note There are different ways to achieve this The above examples show one of several options

31 Fields amp Widgets 21

Django FileBrowser Documentation Release 357

22 Chapter 3 Fields amp Widgets

CHAPTER 4

Admin Interface

41 Admin Interface

The main FileBrowser admin application is an extension for the Django admin interface in order to browser yourmedia folder upload and renamedelete files

411 FileBrowser Site

New in version 340

class FileBrowserSite(name=None app_name=rsquofilebrowserrsquo storage=default_storage)Respresents the FileBrowser admin application (similar to Djangorsquos admin site)

Parameters

bull name ndash A name for the site defaults to None

bull app_name ndash Defaults to lsquofilebrowserrsquo

bull storage ndash A custom storage engine defaults to Djangos default storage

Similar to djangocontribadmin you first need to add a filebrowsersite to your admin interface Inyour urlspy import the default FileBrowser site (or your custom site) and add the site to your URL-patterns (beforeany admin-urls)

from filebrowsersites import site

urlpatterns = patterns(url(r^adminurlfilebrowser include(siteurls))

)

Now you are able to browse the location defined with the storage engine associated to your site

from djangocorefilesstorage import DefaultStoragefrom filebrowsersites import FileBrowserSite

Default FileBrowser sitesite = FileBrowserSite(name=filebrowser storage=DefaultStorage())

My Custom FileBrowser sitecustom_site = FileBrowserSite(name=custom_filebrowser storage=DefaultStorage())custom_sitedirectory = custom_uploads

23

Django FileBrowser Documentation Release 357

Note The module variable site from filebrowsersites is the default FileBrowser application

412 Custom Actions

New in version 340

Similar to Djangorsquos admin actions you can define your FileBrowser actions and thus automate the typical tasks ofyour users Registered custom actions are listed in the detail view of a file and a user can select a single action at atime The selected action will then be applied to the file

The default FileBrowser image actions such as ldquoFlip Verticalrdquo or ldquoRotate 90deg Clockwiserdquo are in fact implemented ascustom actions (see the module filebrowseractions)

Writing Your Own Actions

Custom actions are simple functions

def foo(request fileobjects) Do something with the fileobjects

The first parameter is a HttpRequest object (representing the submitted form in which a user selected the action)and the second parameter is a list of FileObjects to which the action should be applied

The list contains exactly one instance of FileObject (representing the file from the detail view) but this may change inthe future as custom actions may become available also in browse views (similar to admin actions applied to a list ofchecked objects)

Registering an Action

In order to make your action visible you need to register it with a FileBrowser site

siteadd_action(foo)

Once registered the action will appear in the detail view of a file You can also give your action a short description

fooshort_description = Do foo with the File

This short description will then appear in the list of available actions If you do not provide a short description thefunction name will be used instead and FileBrowser will replace any underscores in the function name with spaces

Associating Actions with Specific Files

Each custom action can be associated with a specific file type (eg images audio file etc) to which it applies In orderto do that you need to define a predicatefilter function which takes a single argument (FileObject) and returns Trueif your action is applicable to that FileObject Finally you need to register this filter function with your action

fooapplies_to(lambda fileobject fileobjectfiletype == Image)

In the above example foo will appear in the action list only for image files If you do not specify any filter functionfor your action FileBrowser considers the action as applicable to all files

24 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

Messages amp Intermediate Pages

You can provide a feedback to a user about a successful or failed execution of an action by using a message Forexample

from djangocontrib import messages

def desaturate_image(request fileobjects)for f in fileobjects

Desaturate the imagemessagesadd_message(request messagesSUCCESS _(Image s was desaturated) ffilename)

Some actions may require user confirmation (eg in order to prevent accidental and irreversible modification tofiles) In order to that follow the same pattern as with Djangorsquos admin action and return a HttpResponse objectfrom your action Good practice for intermediate pages is to implement a confirm view and have your action returnHttpResponseRedirect

def crop_image(request fileobjects)files = ampf=join([fpath_relative for f in fileobjects])return HttpResponseRedirect(confirmaction=crop_imageampf=s files)

413 File Storages

New in version 340

You have the option to specify which file storage engine a FileBrowser should use to browseuploadmodify yourmedia files This enables you to use a FileBrowser even if your media files are located at some remote system Seealso the Djangorsquos documentation on storages httpsdocsdjangoprojectcomendevtopicsfiles

To associate a FileBrowser site with a particular storage engine set the storage property of a site object

from djangocorefilesstorage import FileSystemStoragesitestorage = FileSystemStorage(location=pathtomediadirectory base_url=media)

For storage classes other than FileSystemStorage (or those that inherit from that class) therersquos more effort involved inproviding a storage object that can be used with FileBrowser See StorageMixin Class

Note Prior FileBrowser 34 the way to specify FileBrowserlsquos MEDIA_ROOT and MEDIA_URL was via settingspyStarting from version 34 those variables are associated with the storage instance and you can set them as illustratedin the above example

Warning For the reason of backward compatibility FileBrowser settings FILEBROWSER_MEDIA_ROOT andFILEBROWSER_MEDIA_URL can still be used to customize FileBrowser as long as yoursquore using the defaultFileBrowserlsquos site without having changed its storage engine In the next major release of FileBrowser thesesettings will be removed

StorageMixin Class

A FileBrowser uses the Djangorsquos Storage class to access media files However the API of the Storageclass does not provide all methods necessary for FileBrowserrsquos functionality A StorageMixin class fromfilebrowserstorage module therefore defines all the additional methods that a FileBrowser requires

isdir(self name)Returns true if name exists and is a directory

41 Admin Interface 25

Django FileBrowser Documentation Release 357

isfile(self name)Returns true if name exists and is a regular file

move(self old_file_name new_file_name allow_overwrite=False)Moves safely a file from one location to another If allow_ovewrite==False and new_file_nameexists raises an exception

makedirs(self name)Creates all missing directories specified by name Analogue to osmkdirs()

414 Views

All views use the staff_member_requird and path_exists decorator in order to check if the server pathactually exists Some views also use the file_exists decorator

bull Browse fb_browse Browse a directory on your server Returns a FileListing

ndash Optional query string args dir o ot q p filter_date filter_type type

bull Create directory fb_createdir Create a new folder on your server

ndash Optional query string args dir

ndash Signals filebrowser_pre_createdir filebrowser_post_createdir

bull Upload fb_upload Multiple upload

ndash Optional query string args dir type

ndash Signals filebrowser_pre_upload filebrowser_post_upload

bull Edit fb_edit Edit a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_rename filebrowser_post_rename

You are able to apply custom actions (see Custom Actions) to the edit-view

bull Confirm delete fb_confirm_delete Confirm the deletion of a file or folder

ndash Required query string args filename

ndash Optional query string args dir

If you try to delete a folder all filesfolders within this folder are listed on this page

bull Delete fb_delete Delete a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_delete filebrowser_post_delete

Warning If you delete a Folder all items within this Folder are being deleted

bull Version fb_version Generate a version of an image as defined with ADMIN_VERSIONS

ndash Required query string args filename

ndash Optional Query string args dir

This is a helper used by the FileBrowseField and TinyMCE for selecting a version

26 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

415 Signals

The FileBrowser sends a couple of different signals Please take a look at the module filebrowsersignals for furtherexplanation on the provided arguments

bull filebrowser_pre_upload Sent before a an Upload starts

bull filebrowser_post_upload Sent after an Upload has finished

bull filebrowser_pre_delete Sent before an Item (File Folder) is deleted

bull filebrowser_post_delete Sent after an Item (File Folder) has been deleted

bull filebrowser_pre_createdir Sent before a new Folder is created

bull filebrowser_post_createdir Sent after a new Folder has been created

bull filebrowser_pre_rename Sent before an Item (File Folder) is renamed

bull filebrowser_post_rename Sent after an Item (File Folder) has been renamed

bull filebrowser_actions_pre_apply Sent before a custom action is applied

bull filebrowser_actions_post_apply Sent after a custom action has been applied

Example for using these Signals

Herersquos a small example for using the above Signals

from filebrowser import signals

def pre_upload_callback(sender kwargs)Receiver function called before an upload startsprint Pre Upload Callbackprint kwargs kwargs

signalsfilebrowser_pre_uploadconnect(pre_upload_callback)

def post_upload_callback(sender kwargs)Receiver function called each time an upload has finishedprint Post Upload Callbackprint kwargs kwargs You can use all attributes available with the FileObject This is just an example print Filesize kwargs[file]filesizeprint Orientation kwargs[file]orientationprint Extension kwargs[file]extension

signalsfilebrowser_post_uploadconnect(post_upload_callback)

41 Admin Interface 27

Django FileBrowser Documentation Release 357

28 Chapter 4 Admin Interface

CHAPTER 5

Image Versions

51 Versions

With the FileBrowser you are able to define different versionssizes for images This enables you to save an originalimage on your server while having different versions of that image to automatically fit your websites grid Versionsare also useful for responsiveadaptive layouts

511 Defining Versions

New in version 340 methods

First you need to know which versionssizes of an image yoursquod like to generate with your website Letrsquos say yoursquoreusing a 12 column grid with 60px for each column and 20px margin (which is a total of 940px) With this grid youcould (for example) define these image versions

FILEBROWSER_VERSIONS_BASEDIR = _versionsFILEBROWSER_VERSIONS =

admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

Use the methods argument if you need to add a filter

def grayscale(im)Convert image to grayscaleif immode = L

im = imconvert(L)return im

FILEBROWSER_VERSIONS = big verbose_name Big (6 col) width 460 height opts methods [grayscale]

)

29

Django FileBrowser Documentation Release 357

512 Versions and the Admin

When using the FileBrowser with the admin interface you need to define ADMIN_VERSIONS andADMIN_THUMBNAIL (see Settings) ADMIN_VERSIONS are available with the admin ie you are able to seethese versions with the image detail view and you are able to select the versions with the FileBrowseField model field

FILEBROWSER_ADMIN_VERSIONS = [thumbnail small medium big large]FILEBROWSER_ADMIN_THUMBNAIL = admin_thumbnail

513 Versions and the Frontend

With your templates you have two different tags to choose from version and version_object With bothtags the version will be generated if it doesnrsquot already exist OR if the original image is newer than the version Inorder to update an image you just overwrite the original image and the versions will be generated automatically (asyou request them within your template)

A Model example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 blank=True null=True)

With your templates use version if you simply need to retrieve the URL or version_object if you need to geta FileObject

lt-- load filebrowser templatetags --gt load fb_versions

lt-- get the url with version --gtltimg src= version blogentryimage medium gt

lt-- get a fileobject with version_object --gt version_object blogentryimage medium as version_medium version_mediumwidth ltimg src= version_medium gt

Templatetag version

RetrievesGenerates a version and returns an URL

version modelfield_name version_prefix

Templatetag version_object

RetrievesGenerates a version and returns a FileObject

version_object modelfield_name version_prefix as variable

Note With both templatetags version_prefix can either be a string or a variable If version_prefix is astring use quotes

30 Chapter 5 Image Versions

Django FileBrowser Documentation Release 357

514 Versions in Views

If you have a FileObject you can generateretrieve a version with

v = objimageversion_generate(version_prefix) returns a FileObject

515 Placeholder

When developing on a locale machine or a development-server you might not have all the images (resp media-files)available that are on your production instance and downloading these files on a regular basis might not be an option

In that case you can use a placeholder instead of a version You just need to define the PLACEHOLDER and overwritethe settings SHOW_PLACEHOLDER andor FORCE_PLACEHOLDER (see Placeholder)

516 Management Commands

fb_version_generateIf you need to generate certain (or all) versions type

python managepy fb_version_generate

fb_version_removeIf you need to generate certain (or all) versions type

python managepy fb_version_generate

Warning Please be very careful with this command

51 Versions 31

Django FileBrowser Documentation Release 357

32 Chapter 5 Image Versions

CHAPTER 6

Help

61 Help

611 FAQ

Why should I use the FileBrowser

If you need your editors or customers to manage files the FileBrowser is an alternative to an FTP-client Moreoveryou are able to define different image versions according to your websites grid Alternatives to the FileBrowser can befound at httpdjangopackagescomgridsgfile-managers

Do I need Grappelli

Grappelli is a requirement for using the FileBrowser There are several filebrowser-no-grappelli repositories (most ofthem on GitHub) but we donrsquot follow the development

I need help

see Troubleshooting

Why are there no fancy effects

The FileBrowser is about managing files We think that you should prepare your files before uploading them to theserver

How do I upload to another server

Use a custom storage engine see httpsdocsdjangoprojectcomen16howtocustom-file-storage

Why do I need image-versions

You need image-versions if your website is based on a grid

33

Django FileBrowser Documentation Release 357

Is the FileBrowser stable

Wersquove developed the FileBrowser for a couple of years and use it with almost all of our clients That said Grappelli isthe more stable and mature application

How can I contribute

Help is very much needed and appreciated Test the FileBrowser and submit feedbackpatches

Who develops the FileBrowser

The FileBrowser is developed and maintained by Patrick Kranzlmuumlller amp Axel Swoboda of vonautomatisch

612 Troubleshooting

Check your setup

Please check if the problem is caused by your setup

bull Read Quick start guide

bull Check if the staticmedia-files are served correctly

bull Make sure you have removed all custom FileBrowser templates from all locations in TEMPLATE_DIRS orcheck that these templates are compatible with the FileBrowser

Run the tests

Start the shell and type

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Check issues

If your setup is fine please check if your problem is a known issue

bull Take a look at all FileBrowser Issues (incuding closed) and search the FileBrowser Google-Group

Add a ticket

If you think yoursquove found a bug please add a ticket

bull Try to describe your problem as precisely as possible

bull Tell us what you did in order to solve the problem

bull Tell us what version of the FileBrowser you are using

bull Tell us what version of Django you are using

34 Chapter 6 Help

Django FileBrowser Documentation Release 357

bull Please do NOT add tickets if yoursquore having problems with serving staticmedia-files (because this is not relatedto the FileBrowser)

bull Please do NOT add tickets referring to Djangos trunk version

bull At best add a patch

Note Be aware that we may close issues not following these guidlines without further notifications

613 Translation

Translation is done via Transifex

Supported Languages

see httpswwwtransifexnetprojectspdjango-filebrowserresourcedjangopo

614 FileBrowser 35 Release Notes

FileBrowser 35 is compatible with Django 14151617 as well as Grappelli 242526

Update from FileBrowser 34x

bull Update Django to 14151617 and check httpsdocsdjangoprojectcomendevreleases14 orhttpsdocsdjangoprojectcomendevreleases15 or httpsdocsdjangoprojectcomendevreleases16

bull Update Grappelli to 24x25x26x

bull Update FileBrowser to 35x

62 Changelog

621 358 (not yet released)

622 357 (September 10th 2014)

bull New Compatibility with Django 17 and Grappelli 26x

bull Improved Updated tests because of the new random suffix with get_available_name (django storage)

bull Improved Added an icon in order to mark finished uploads

bull Improved Show resulting filename (eg with suffix converted) after successful upload

bull Fixed Permissions with file upload

bull Fixed Unified json response with _upload_file (no matter if file already exists or not)

623 356 (April 16th 2014)

bull Fixed Displaying pagination correctly with lots of entries

62 Changelog 35

Django FileBrowser Documentation Release 357

624 355 (April 13th 2014)

bull New Added client-side (JavaScript) file extension validation to the AJAX uploader

bull New Added experimental Python 33 support

bull Improved Tests with convertnormalize (removed special chars from test filename)

bull Fixed File selection after using search box (CKEditor)

bull Fixed Removed encoding of file URIs with CKEditor

625 354 (February 21st 2014)

bull Fixed Placeholder functionality (including tests)

bull Fixed Convertnormalize filenames (including tests)

bull Fixed Handling uppercase extensions with browse

626 353 (January 7 2014)

bull New added path_full to FileObject

bull Improved added docx to EXTENSIONS

bull Improved Recommend pillow instead of PIL as a requirement

bull Improved Added additional test cases

bull Improved Updated documentation

bull Improved Consistent use of storage (eg storagelocation storageurl)

bull Improved Removed unnecessary functions (eg url_join url_strip)

bull Improved Moved sort_by_attr to FileListing

bull Improved Regex matches with file versions on browse

bull Improved Using djangoconfurls (with djangoconfurlsdefaults as fallback)

bull Improved Adding CONTRIBUTINGrst

bull Improved Removed static Media inner class with fields

bull Improved Removed search icon with fields (has not being used)

bull Improved Added custom class attributes with filebrowser field

bull Improved Updated translations

bull Fixed fixed exception handling with python 25

bull Fixed fixes dir with SEARCH_TRAVERSE true and version select

bull Fixed Make Django FileUploadHandlers work (also fixed a memory leak)

bull Fixed return correct filename with OVERWRITE_EXISTING

bull Fixed fb_version_generate with FILEBROWSER_VERSIONS_BASEDIR

bull Fixed Table sorting with ascdesc

bull Fixed Added DeprecationWarning for FileObjectdirectory and FileObjectfolder

36 Chapter 6 Help

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

Django FileBrowser Documentation Release 357

Showing Thumbnail in the Changelist

To show a thumbnail with the changelist you can define a ModelAdmin method

from filebrowsersettings import ADMIN_THUMBNAIL

def image_thumbnail(self obj)if objimage and objimagefiletype == Image

return ltimg src=s gt objimageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Using the FileBrowseField with TinyMCE

In order to replace the TinyMCE imagefile manager with the FileBrowser you have to use a FileBrowser CallbackTherersquos an example TinyMCE configuration file in staticjs called TinyMCEAdminjs You can either copy theFileBrowserCallback to your own file or just use tinymce_setupjs (which comes with django-grappelli)

Just add these lines to your ModelAdmin asset definitions

class Mediajs = [pathtotinymcejscriptstiny_mcetiny_mcejs

pathtoyourtinymce_setupjs]

312 FileInput

Subclass of FileInput with an additional thumbnail

from filebrowserwidgets import FileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget FileInput

313 ClearableFileInput

Subclass of ClearableFileInput with an additional thumbnail

from filebrowserwidgets import ClearableFileInput

class BlogEntryOptions(adminModelAdmin)formfield_overrides =

modelsImageField widget ClearableFileInput

314 Django FileField and the FileBrowser

Return a FileObject from a FileField or ImageField with

20 Chapter 3 Fields amp Widgets

Django FileBrowser Documentation Release 357

from filebrowserbase import FileObject

image_upload = modelsImageField(uImage (Upload) max_length=250 upload_to=image_upload_path blank=True null=True)

def image(self)if selfimage_upload

return FileObject(selfimage_uploadpath)return None

In order show a thumbnail with your changelist you could use a ModelAdmin method

from filebrowserbase import FileObject

def image_thumbnail(self obj)if objimage_upload

image = FileObject(objimage_uploadpath)if imagefiletype == Image

return ltimg src=s gt imageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Note There are different ways to achieve this The above examples show one of several options

31 Fields amp Widgets 21

Django FileBrowser Documentation Release 357

22 Chapter 3 Fields amp Widgets

CHAPTER 4

Admin Interface

41 Admin Interface

The main FileBrowser admin application is an extension for the Django admin interface in order to browser yourmedia folder upload and renamedelete files

411 FileBrowser Site

New in version 340

class FileBrowserSite(name=None app_name=rsquofilebrowserrsquo storage=default_storage)Respresents the FileBrowser admin application (similar to Djangorsquos admin site)

Parameters

bull name ndash A name for the site defaults to None

bull app_name ndash Defaults to lsquofilebrowserrsquo

bull storage ndash A custom storage engine defaults to Djangos default storage

Similar to djangocontribadmin you first need to add a filebrowsersite to your admin interface Inyour urlspy import the default FileBrowser site (or your custom site) and add the site to your URL-patterns (beforeany admin-urls)

from filebrowsersites import site

urlpatterns = patterns(url(r^adminurlfilebrowser include(siteurls))

)

Now you are able to browse the location defined with the storage engine associated to your site

from djangocorefilesstorage import DefaultStoragefrom filebrowsersites import FileBrowserSite

Default FileBrowser sitesite = FileBrowserSite(name=filebrowser storage=DefaultStorage())

My Custom FileBrowser sitecustom_site = FileBrowserSite(name=custom_filebrowser storage=DefaultStorage())custom_sitedirectory = custom_uploads

23

Django FileBrowser Documentation Release 357

Note The module variable site from filebrowsersites is the default FileBrowser application

412 Custom Actions

New in version 340

Similar to Djangorsquos admin actions you can define your FileBrowser actions and thus automate the typical tasks ofyour users Registered custom actions are listed in the detail view of a file and a user can select a single action at atime The selected action will then be applied to the file

The default FileBrowser image actions such as ldquoFlip Verticalrdquo or ldquoRotate 90deg Clockwiserdquo are in fact implemented ascustom actions (see the module filebrowseractions)

Writing Your Own Actions

Custom actions are simple functions

def foo(request fileobjects) Do something with the fileobjects

The first parameter is a HttpRequest object (representing the submitted form in which a user selected the action)and the second parameter is a list of FileObjects to which the action should be applied

The list contains exactly one instance of FileObject (representing the file from the detail view) but this may change inthe future as custom actions may become available also in browse views (similar to admin actions applied to a list ofchecked objects)

Registering an Action

In order to make your action visible you need to register it with a FileBrowser site

siteadd_action(foo)

Once registered the action will appear in the detail view of a file You can also give your action a short description

fooshort_description = Do foo with the File

This short description will then appear in the list of available actions If you do not provide a short description thefunction name will be used instead and FileBrowser will replace any underscores in the function name with spaces

Associating Actions with Specific Files

Each custom action can be associated with a specific file type (eg images audio file etc) to which it applies In orderto do that you need to define a predicatefilter function which takes a single argument (FileObject) and returns Trueif your action is applicable to that FileObject Finally you need to register this filter function with your action

fooapplies_to(lambda fileobject fileobjectfiletype == Image)

In the above example foo will appear in the action list only for image files If you do not specify any filter functionfor your action FileBrowser considers the action as applicable to all files

24 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

Messages amp Intermediate Pages

You can provide a feedback to a user about a successful or failed execution of an action by using a message Forexample

from djangocontrib import messages

def desaturate_image(request fileobjects)for f in fileobjects

Desaturate the imagemessagesadd_message(request messagesSUCCESS _(Image s was desaturated) ffilename)

Some actions may require user confirmation (eg in order to prevent accidental and irreversible modification tofiles) In order to that follow the same pattern as with Djangorsquos admin action and return a HttpResponse objectfrom your action Good practice for intermediate pages is to implement a confirm view and have your action returnHttpResponseRedirect

def crop_image(request fileobjects)files = ampf=join([fpath_relative for f in fileobjects])return HttpResponseRedirect(confirmaction=crop_imageampf=s files)

413 File Storages

New in version 340

You have the option to specify which file storage engine a FileBrowser should use to browseuploadmodify yourmedia files This enables you to use a FileBrowser even if your media files are located at some remote system Seealso the Djangorsquos documentation on storages httpsdocsdjangoprojectcomendevtopicsfiles

To associate a FileBrowser site with a particular storage engine set the storage property of a site object

from djangocorefilesstorage import FileSystemStoragesitestorage = FileSystemStorage(location=pathtomediadirectory base_url=media)

For storage classes other than FileSystemStorage (or those that inherit from that class) therersquos more effort involved inproviding a storage object that can be used with FileBrowser See StorageMixin Class

Note Prior FileBrowser 34 the way to specify FileBrowserlsquos MEDIA_ROOT and MEDIA_URL was via settingspyStarting from version 34 those variables are associated with the storage instance and you can set them as illustratedin the above example

Warning For the reason of backward compatibility FileBrowser settings FILEBROWSER_MEDIA_ROOT andFILEBROWSER_MEDIA_URL can still be used to customize FileBrowser as long as yoursquore using the defaultFileBrowserlsquos site without having changed its storage engine In the next major release of FileBrowser thesesettings will be removed

StorageMixin Class

A FileBrowser uses the Djangorsquos Storage class to access media files However the API of the Storageclass does not provide all methods necessary for FileBrowserrsquos functionality A StorageMixin class fromfilebrowserstorage module therefore defines all the additional methods that a FileBrowser requires

isdir(self name)Returns true if name exists and is a directory

41 Admin Interface 25

Django FileBrowser Documentation Release 357

isfile(self name)Returns true if name exists and is a regular file

move(self old_file_name new_file_name allow_overwrite=False)Moves safely a file from one location to another If allow_ovewrite==False and new_file_nameexists raises an exception

makedirs(self name)Creates all missing directories specified by name Analogue to osmkdirs()

414 Views

All views use the staff_member_requird and path_exists decorator in order to check if the server pathactually exists Some views also use the file_exists decorator

bull Browse fb_browse Browse a directory on your server Returns a FileListing

ndash Optional query string args dir o ot q p filter_date filter_type type

bull Create directory fb_createdir Create a new folder on your server

ndash Optional query string args dir

ndash Signals filebrowser_pre_createdir filebrowser_post_createdir

bull Upload fb_upload Multiple upload

ndash Optional query string args dir type

ndash Signals filebrowser_pre_upload filebrowser_post_upload

bull Edit fb_edit Edit a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_rename filebrowser_post_rename

You are able to apply custom actions (see Custom Actions) to the edit-view

bull Confirm delete fb_confirm_delete Confirm the deletion of a file or folder

ndash Required query string args filename

ndash Optional query string args dir

If you try to delete a folder all filesfolders within this folder are listed on this page

bull Delete fb_delete Delete a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_delete filebrowser_post_delete

Warning If you delete a Folder all items within this Folder are being deleted

bull Version fb_version Generate a version of an image as defined with ADMIN_VERSIONS

ndash Required query string args filename

ndash Optional Query string args dir

This is a helper used by the FileBrowseField and TinyMCE for selecting a version

26 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

415 Signals

The FileBrowser sends a couple of different signals Please take a look at the module filebrowsersignals for furtherexplanation on the provided arguments

bull filebrowser_pre_upload Sent before a an Upload starts

bull filebrowser_post_upload Sent after an Upload has finished

bull filebrowser_pre_delete Sent before an Item (File Folder) is deleted

bull filebrowser_post_delete Sent after an Item (File Folder) has been deleted

bull filebrowser_pre_createdir Sent before a new Folder is created

bull filebrowser_post_createdir Sent after a new Folder has been created

bull filebrowser_pre_rename Sent before an Item (File Folder) is renamed

bull filebrowser_post_rename Sent after an Item (File Folder) has been renamed

bull filebrowser_actions_pre_apply Sent before a custom action is applied

bull filebrowser_actions_post_apply Sent after a custom action has been applied

Example for using these Signals

Herersquos a small example for using the above Signals

from filebrowser import signals

def pre_upload_callback(sender kwargs)Receiver function called before an upload startsprint Pre Upload Callbackprint kwargs kwargs

signalsfilebrowser_pre_uploadconnect(pre_upload_callback)

def post_upload_callback(sender kwargs)Receiver function called each time an upload has finishedprint Post Upload Callbackprint kwargs kwargs You can use all attributes available with the FileObject This is just an example print Filesize kwargs[file]filesizeprint Orientation kwargs[file]orientationprint Extension kwargs[file]extension

signalsfilebrowser_post_uploadconnect(post_upload_callback)

41 Admin Interface 27

Django FileBrowser Documentation Release 357

28 Chapter 4 Admin Interface

CHAPTER 5

Image Versions

51 Versions

With the FileBrowser you are able to define different versionssizes for images This enables you to save an originalimage on your server while having different versions of that image to automatically fit your websites grid Versionsare also useful for responsiveadaptive layouts

511 Defining Versions

New in version 340 methods

First you need to know which versionssizes of an image yoursquod like to generate with your website Letrsquos say yoursquoreusing a 12 column grid with 60px for each column and 20px margin (which is a total of 940px) With this grid youcould (for example) define these image versions

FILEBROWSER_VERSIONS_BASEDIR = _versionsFILEBROWSER_VERSIONS =

admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

Use the methods argument if you need to add a filter

def grayscale(im)Convert image to grayscaleif immode = L

im = imconvert(L)return im

FILEBROWSER_VERSIONS = big verbose_name Big (6 col) width 460 height opts methods [grayscale]

)

29

Django FileBrowser Documentation Release 357

512 Versions and the Admin

When using the FileBrowser with the admin interface you need to define ADMIN_VERSIONS andADMIN_THUMBNAIL (see Settings) ADMIN_VERSIONS are available with the admin ie you are able to seethese versions with the image detail view and you are able to select the versions with the FileBrowseField model field

FILEBROWSER_ADMIN_VERSIONS = [thumbnail small medium big large]FILEBROWSER_ADMIN_THUMBNAIL = admin_thumbnail

513 Versions and the Frontend

With your templates you have two different tags to choose from version and version_object With bothtags the version will be generated if it doesnrsquot already exist OR if the original image is newer than the version Inorder to update an image you just overwrite the original image and the versions will be generated automatically (asyou request them within your template)

A Model example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 blank=True null=True)

With your templates use version if you simply need to retrieve the URL or version_object if you need to geta FileObject

lt-- load filebrowser templatetags --gt load fb_versions

lt-- get the url with version --gtltimg src= version blogentryimage medium gt

lt-- get a fileobject with version_object --gt version_object blogentryimage medium as version_medium version_mediumwidth ltimg src= version_medium gt

Templatetag version

RetrievesGenerates a version and returns an URL

version modelfield_name version_prefix

Templatetag version_object

RetrievesGenerates a version and returns a FileObject

version_object modelfield_name version_prefix as variable

Note With both templatetags version_prefix can either be a string or a variable If version_prefix is astring use quotes

30 Chapter 5 Image Versions

Django FileBrowser Documentation Release 357

514 Versions in Views

If you have a FileObject you can generateretrieve a version with

v = objimageversion_generate(version_prefix) returns a FileObject

515 Placeholder

When developing on a locale machine or a development-server you might not have all the images (resp media-files)available that are on your production instance and downloading these files on a regular basis might not be an option

In that case you can use a placeholder instead of a version You just need to define the PLACEHOLDER and overwritethe settings SHOW_PLACEHOLDER andor FORCE_PLACEHOLDER (see Placeholder)

516 Management Commands

fb_version_generateIf you need to generate certain (or all) versions type

python managepy fb_version_generate

fb_version_removeIf you need to generate certain (or all) versions type

python managepy fb_version_generate

Warning Please be very careful with this command

51 Versions 31

Django FileBrowser Documentation Release 357

32 Chapter 5 Image Versions

CHAPTER 6

Help

61 Help

611 FAQ

Why should I use the FileBrowser

If you need your editors or customers to manage files the FileBrowser is an alternative to an FTP-client Moreoveryou are able to define different image versions according to your websites grid Alternatives to the FileBrowser can befound at httpdjangopackagescomgridsgfile-managers

Do I need Grappelli

Grappelli is a requirement for using the FileBrowser There are several filebrowser-no-grappelli repositories (most ofthem on GitHub) but we donrsquot follow the development

I need help

see Troubleshooting

Why are there no fancy effects

The FileBrowser is about managing files We think that you should prepare your files before uploading them to theserver

How do I upload to another server

Use a custom storage engine see httpsdocsdjangoprojectcomen16howtocustom-file-storage

Why do I need image-versions

You need image-versions if your website is based on a grid

33

Django FileBrowser Documentation Release 357

Is the FileBrowser stable

Wersquove developed the FileBrowser for a couple of years and use it with almost all of our clients That said Grappelli isthe more stable and mature application

How can I contribute

Help is very much needed and appreciated Test the FileBrowser and submit feedbackpatches

Who develops the FileBrowser

The FileBrowser is developed and maintained by Patrick Kranzlmuumlller amp Axel Swoboda of vonautomatisch

612 Troubleshooting

Check your setup

Please check if the problem is caused by your setup

bull Read Quick start guide

bull Check if the staticmedia-files are served correctly

bull Make sure you have removed all custom FileBrowser templates from all locations in TEMPLATE_DIRS orcheck that these templates are compatible with the FileBrowser

Run the tests

Start the shell and type

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Check issues

If your setup is fine please check if your problem is a known issue

bull Take a look at all FileBrowser Issues (incuding closed) and search the FileBrowser Google-Group

Add a ticket

If you think yoursquove found a bug please add a ticket

bull Try to describe your problem as precisely as possible

bull Tell us what you did in order to solve the problem

bull Tell us what version of the FileBrowser you are using

bull Tell us what version of Django you are using

34 Chapter 6 Help

Django FileBrowser Documentation Release 357

bull Please do NOT add tickets if yoursquore having problems with serving staticmedia-files (because this is not relatedto the FileBrowser)

bull Please do NOT add tickets referring to Djangos trunk version

bull At best add a patch

Note Be aware that we may close issues not following these guidlines without further notifications

613 Translation

Translation is done via Transifex

Supported Languages

see httpswwwtransifexnetprojectspdjango-filebrowserresourcedjangopo

614 FileBrowser 35 Release Notes

FileBrowser 35 is compatible with Django 14151617 as well as Grappelli 242526

Update from FileBrowser 34x

bull Update Django to 14151617 and check httpsdocsdjangoprojectcomendevreleases14 orhttpsdocsdjangoprojectcomendevreleases15 or httpsdocsdjangoprojectcomendevreleases16

bull Update Grappelli to 24x25x26x

bull Update FileBrowser to 35x

62 Changelog

621 358 (not yet released)

622 357 (September 10th 2014)

bull New Compatibility with Django 17 and Grappelli 26x

bull Improved Updated tests because of the new random suffix with get_available_name (django storage)

bull Improved Added an icon in order to mark finished uploads

bull Improved Show resulting filename (eg with suffix converted) after successful upload

bull Fixed Permissions with file upload

bull Fixed Unified json response with _upload_file (no matter if file already exists or not)

623 356 (April 16th 2014)

bull Fixed Displaying pagination correctly with lots of entries

62 Changelog 35

Django FileBrowser Documentation Release 357

624 355 (April 13th 2014)

bull New Added client-side (JavaScript) file extension validation to the AJAX uploader

bull New Added experimental Python 33 support

bull Improved Tests with convertnormalize (removed special chars from test filename)

bull Fixed File selection after using search box (CKEditor)

bull Fixed Removed encoding of file URIs with CKEditor

625 354 (February 21st 2014)

bull Fixed Placeholder functionality (including tests)

bull Fixed Convertnormalize filenames (including tests)

bull Fixed Handling uppercase extensions with browse

626 353 (January 7 2014)

bull New added path_full to FileObject

bull Improved added docx to EXTENSIONS

bull Improved Recommend pillow instead of PIL as a requirement

bull Improved Added additional test cases

bull Improved Updated documentation

bull Improved Consistent use of storage (eg storagelocation storageurl)

bull Improved Removed unnecessary functions (eg url_join url_strip)

bull Improved Moved sort_by_attr to FileListing

bull Improved Regex matches with file versions on browse

bull Improved Using djangoconfurls (with djangoconfurlsdefaults as fallback)

bull Improved Adding CONTRIBUTINGrst

bull Improved Removed static Media inner class with fields

bull Improved Removed search icon with fields (has not being used)

bull Improved Added custom class attributes with filebrowser field

bull Improved Updated translations

bull Fixed fixed exception handling with python 25

bull Fixed fixes dir with SEARCH_TRAVERSE true and version select

bull Fixed Make Django FileUploadHandlers work (also fixed a memory leak)

bull Fixed return correct filename with OVERWRITE_EXISTING

bull Fixed fb_version_generate with FILEBROWSER_VERSIONS_BASEDIR

bull Fixed Table sorting with ascdesc

bull Fixed Added DeprecationWarning for FileObjectdirectory and FileObjectfolder

36 Chapter 6 Help

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

Django FileBrowser Documentation Release 357

from filebrowserbase import FileObject

image_upload = modelsImageField(uImage (Upload) max_length=250 upload_to=image_upload_path blank=True null=True)

def image(self)if selfimage_upload

return FileObject(selfimage_uploadpath)return None

In order show a thumbnail with your changelist you could use a ModelAdmin method

from filebrowserbase import FileObject

def image_thumbnail(self obj)if objimage_upload

image = FileObject(objimage_uploadpath)if imagefiletype == Image

return ltimg src=s gt imageversion_generate(ADMIN_THUMBNAIL)urlelse

return image_thumbnailallow_tags = Trueimage_thumbnailshort_description = Thumbnail

Note There are different ways to achieve this The above examples show one of several options

31 Fields amp Widgets 21

Django FileBrowser Documentation Release 357

22 Chapter 3 Fields amp Widgets

CHAPTER 4

Admin Interface

41 Admin Interface

The main FileBrowser admin application is an extension for the Django admin interface in order to browser yourmedia folder upload and renamedelete files

411 FileBrowser Site

New in version 340

class FileBrowserSite(name=None app_name=rsquofilebrowserrsquo storage=default_storage)Respresents the FileBrowser admin application (similar to Djangorsquos admin site)

Parameters

bull name ndash A name for the site defaults to None

bull app_name ndash Defaults to lsquofilebrowserrsquo

bull storage ndash A custom storage engine defaults to Djangos default storage

Similar to djangocontribadmin you first need to add a filebrowsersite to your admin interface Inyour urlspy import the default FileBrowser site (or your custom site) and add the site to your URL-patterns (beforeany admin-urls)

from filebrowsersites import site

urlpatterns = patterns(url(r^adminurlfilebrowser include(siteurls))

)

Now you are able to browse the location defined with the storage engine associated to your site

from djangocorefilesstorage import DefaultStoragefrom filebrowsersites import FileBrowserSite

Default FileBrowser sitesite = FileBrowserSite(name=filebrowser storage=DefaultStorage())

My Custom FileBrowser sitecustom_site = FileBrowserSite(name=custom_filebrowser storage=DefaultStorage())custom_sitedirectory = custom_uploads

23

Django FileBrowser Documentation Release 357

Note The module variable site from filebrowsersites is the default FileBrowser application

412 Custom Actions

New in version 340

Similar to Djangorsquos admin actions you can define your FileBrowser actions and thus automate the typical tasks ofyour users Registered custom actions are listed in the detail view of a file and a user can select a single action at atime The selected action will then be applied to the file

The default FileBrowser image actions such as ldquoFlip Verticalrdquo or ldquoRotate 90deg Clockwiserdquo are in fact implemented ascustom actions (see the module filebrowseractions)

Writing Your Own Actions

Custom actions are simple functions

def foo(request fileobjects) Do something with the fileobjects

The first parameter is a HttpRequest object (representing the submitted form in which a user selected the action)and the second parameter is a list of FileObjects to which the action should be applied

The list contains exactly one instance of FileObject (representing the file from the detail view) but this may change inthe future as custom actions may become available also in browse views (similar to admin actions applied to a list ofchecked objects)

Registering an Action

In order to make your action visible you need to register it with a FileBrowser site

siteadd_action(foo)

Once registered the action will appear in the detail view of a file You can also give your action a short description

fooshort_description = Do foo with the File

This short description will then appear in the list of available actions If you do not provide a short description thefunction name will be used instead and FileBrowser will replace any underscores in the function name with spaces

Associating Actions with Specific Files

Each custom action can be associated with a specific file type (eg images audio file etc) to which it applies In orderto do that you need to define a predicatefilter function which takes a single argument (FileObject) and returns Trueif your action is applicable to that FileObject Finally you need to register this filter function with your action

fooapplies_to(lambda fileobject fileobjectfiletype == Image)

In the above example foo will appear in the action list only for image files If you do not specify any filter functionfor your action FileBrowser considers the action as applicable to all files

24 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

Messages amp Intermediate Pages

You can provide a feedback to a user about a successful or failed execution of an action by using a message Forexample

from djangocontrib import messages

def desaturate_image(request fileobjects)for f in fileobjects

Desaturate the imagemessagesadd_message(request messagesSUCCESS _(Image s was desaturated) ffilename)

Some actions may require user confirmation (eg in order to prevent accidental and irreversible modification tofiles) In order to that follow the same pattern as with Djangorsquos admin action and return a HttpResponse objectfrom your action Good practice for intermediate pages is to implement a confirm view and have your action returnHttpResponseRedirect

def crop_image(request fileobjects)files = ampf=join([fpath_relative for f in fileobjects])return HttpResponseRedirect(confirmaction=crop_imageampf=s files)

413 File Storages

New in version 340

You have the option to specify which file storage engine a FileBrowser should use to browseuploadmodify yourmedia files This enables you to use a FileBrowser even if your media files are located at some remote system Seealso the Djangorsquos documentation on storages httpsdocsdjangoprojectcomendevtopicsfiles

To associate a FileBrowser site with a particular storage engine set the storage property of a site object

from djangocorefilesstorage import FileSystemStoragesitestorage = FileSystemStorage(location=pathtomediadirectory base_url=media)

For storage classes other than FileSystemStorage (or those that inherit from that class) therersquos more effort involved inproviding a storage object that can be used with FileBrowser See StorageMixin Class

Note Prior FileBrowser 34 the way to specify FileBrowserlsquos MEDIA_ROOT and MEDIA_URL was via settingspyStarting from version 34 those variables are associated with the storage instance and you can set them as illustratedin the above example

Warning For the reason of backward compatibility FileBrowser settings FILEBROWSER_MEDIA_ROOT andFILEBROWSER_MEDIA_URL can still be used to customize FileBrowser as long as yoursquore using the defaultFileBrowserlsquos site without having changed its storage engine In the next major release of FileBrowser thesesettings will be removed

StorageMixin Class

A FileBrowser uses the Djangorsquos Storage class to access media files However the API of the Storageclass does not provide all methods necessary for FileBrowserrsquos functionality A StorageMixin class fromfilebrowserstorage module therefore defines all the additional methods that a FileBrowser requires

isdir(self name)Returns true if name exists and is a directory

41 Admin Interface 25

Django FileBrowser Documentation Release 357

isfile(self name)Returns true if name exists and is a regular file

move(self old_file_name new_file_name allow_overwrite=False)Moves safely a file from one location to another If allow_ovewrite==False and new_file_nameexists raises an exception

makedirs(self name)Creates all missing directories specified by name Analogue to osmkdirs()

414 Views

All views use the staff_member_requird and path_exists decorator in order to check if the server pathactually exists Some views also use the file_exists decorator

bull Browse fb_browse Browse a directory on your server Returns a FileListing

ndash Optional query string args dir o ot q p filter_date filter_type type

bull Create directory fb_createdir Create a new folder on your server

ndash Optional query string args dir

ndash Signals filebrowser_pre_createdir filebrowser_post_createdir

bull Upload fb_upload Multiple upload

ndash Optional query string args dir type

ndash Signals filebrowser_pre_upload filebrowser_post_upload

bull Edit fb_edit Edit a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_rename filebrowser_post_rename

You are able to apply custom actions (see Custom Actions) to the edit-view

bull Confirm delete fb_confirm_delete Confirm the deletion of a file or folder

ndash Required query string args filename

ndash Optional query string args dir

If you try to delete a folder all filesfolders within this folder are listed on this page

bull Delete fb_delete Delete a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_delete filebrowser_post_delete

Warning If you delete a Folder all items within this Folder are being deleted

bull Version fb_version Generate a version of an image as defined with ADMIN_VERSIONS

ndash Required query string args filename

ndash Optional Query string args dir

This is a helper used by the FileBrowseField and TinyMCE for selecting a version

26 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

415 Signals

The FileBrowser sends a couple of different signals Please take a look at the module filebrowsersignals for furtherexplanation on the provided arguments

bull filebrowser_pre_upload Sent before a an Upload starts

bull filebrowser_post_upload Sent after an Upload has finished

bull filebrowser_pre_delete Sent before an Item (File Folder) is deleted

bull filebrowser_post_delete Sent after an Item (File Folder) has been deleted

bull filebrowser_pre_createdir Sent before a new Folder is created

bull filebrowser_post_createdir Sent after a new Folder has been created

bull filebrowser_pre_rename Sent before an Item (File Folder) is renamed

bull filebrowser_post_rename Sent after an Item (File Folder) has been renamed

bull filebrowser_actions_pre_apply Sent before a custom action is applied

bull filebrowser_actions_post_apply Sent after a custom action has been applied

Example for using these Signals

Herersquos a small example for using the above Signals

from filebrowser import signals

def pre_upload_callback(sender kwargs)Receiver function called before an upload startsprint Pre Upload Callbackprint kwargs kwargs

signalsfilebrowser_pre_uploadconnect(pre_upload_callback)

def post_upload_callback(sender kwargs)Receiver function called each time an upload has finishedprint Post Upload Callbackprint kwargs kwargs You can use all attributes available with the FileObject This is just an example print Filesize kwargs[file]filesizeprint Orientation kwargs[file]orientationprint Extension kwargs[file]extension

signalsfilebrowser_post_uploadconnect(post_upload_callback)

41 Admin Interface 27

Django FileBrowser Documentation Release 357

28 Chapter 4 Admin Interface

CHAPTER 5

Image Versions

51 Versions

With the FileBrowser you are able to define different versionssizes for images This enables you to save an originalimage on your server while having different versions of that image to automatically fit your websites grid Versionsare also useful for responsiveadaptive layouts

511 Defining Versions

New in version 340 methods

First you need to know which versionssizes of an image yoursquod like to generate with your website Letrsquos say yoursquoreusing a 12 column grid with 60px for each column and 20px margin (which is a total of 940px) With this grid youcould (for example) define these image versions

FILEBROWSER_VERSIONS_BASEDIR = _versionsFILEBROWSER_VERSIONS =

admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

Use the methods argument if you need to add a filter

def grayscale(im)Convert image to grayscaleif immode = L

im = imconvert(L)return im

FILEBROWSER_VERSIONS = big verbose_name Big (6 col) width 460 height opts methods [grayscale]

)

29

Django FileBrowser Documentation Release 357

512 Versions and the Admin

When using the FileBrowser with the admin interface you need to define ADMIN_VERSIONS andADMIN_THUMBNAIL (see Settings) ADMIN_VERSIONS are available with the admin ie you are able to seethese versions with the image detail view and you are able to select the versions with the FileBrowseField model field

FILEBROWSER_ADMIN_VERSIONS = [thumbnail small medium big large]FILEBROWSER_ADMIN_THUMBNAIL = admin_thumbnail

513 Versions and the Frontend

With your templates you have two different tags to choose from version and version_object With bothtags the version will be generated if it doesnrsquot already exist OR if the original image is newer than the version Inorder to update an image you just overwrite the original image and the versions will be generated automatically (asyou request them within your template)

A Model example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 blank=True null=True)

With your templates use version if you simply need to retrieve the URL or version_object if you need to geta FileObject

lt-- load filebrowser templatetags --gt load fb_versions

lt-- get the url with version --gtltimg src= version blogentryimage medium gt

lt-- get a fileobject with version_object --gt version_object blogentryimage medium as version_medium version_mediumwidth ltimg src= version_medium gt

Templatetag version

RetrievesGenerates a version and returns an URL

version modelfield_name version_prefix

Templatetag version_object

RetrievesGenerates a version and returns a FileObject

version_object modelfield_name version_prefix as variable

Note With both templatetags version_prefix can either be a string or a variable If version_prefix is astring use quotes

30 Chapter 5 Image Versions

Django FileBrowser Documentation Release 357

514 Versions in Views

If you have a FileObject you can generateretrieve a version with

v = objimageversion_generate(version_prefix) returns a FileObject

515 Placeholder

When developing on a locale machine or a development-server you might not have all the images (resp media-files)available that are on your production instance and downloading these files on a regular basis might not be an option

In that case you can use a placeholder instead of a version You just need to define the PLACEHOLDER and overwritethe settings SHOW_PLACEHOLDER andor FORCE_PLACEHOLDER (see Placeholder)

516 Management Commands

fb_version_generateIf you need to generate certain (or all) versions type

python managepy fb_version_generate

fb_version_removeIf you need to generate certain (or all) versions type

python managepy fb_version_generate

Warning Please be very careful with this command

51 Versions 31

Django FileBrowser Documentation Release 357

32 Chapter 5 Image Versions

CHAPTER 6

Help

61 Help

611 FAQ

Why should I use the FileBrowser

If you need your editors or customers to manage files the FileBrowser is an alternative to an FTP-client Moreoveryou are able to define different image versions according to your websites grid Alternatives to the FileBrowser can befound at httpdjangopackagescomgridsgfile-managers

Do I need Grappelli

Grappelli is a requirement for using the FileBrowser There are several filebrowser-no-grappelli repositories (most ofthem on GitHub) but we donrsquot follow the development

I need help

see Troubleshooting

Why are there no fancy effects

The FileBrowser is about managing files We think that you should prepare your files before uploading them to theserver

How do I upload to another server

Use a custom storage engine see httpsdocsdjangoprojectcomen16howtocustom-file-storage

Why do I need image-versions

You need image-versions if your website is based on a grid

33

Django FileBrowser Documentation Release 357

Is the FileBrowser stable

Wersquove developed the FileBrowser for a couple of years and use it with almost all of our clients That said Grappelli isthe more stable and mature application

How can I contribute

Help is very much needed and appreciated Test the FileBrowser and submit feedbackpatches

Who develops the FileBrowser

The FileBrowser is developed and maintained by Patrick Kranzlmuumlller amp Axel Swoboda of vonautomatisch

612 Troubleshooting

Check your setup

Please check if the problem is caused by your setup

bull Read Quick start guide

bull Check if the staticmedia-files are served correctly

bull Make sure you have removed all custom FileBrowser templates from all locations in TEMPLATE_DIRS orcheck that these templates are compatible with the FileBrowser

Run the tests

Start the shell and type

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Check issues

If your setup is fine please check if your problem is a known issue

bull Take a look at all FileBrowser Issues (incuding closed) and search the FileBrowser Google-Group

Add a ticket

If you think yoursquove found a bug please add a ticket

bull Try to describe your problem as precisely as possible

bull Tell us what you did in order to solve the problem

bull Tell us what version of the FileBrowser you are using

bull Tell us what version of Django you are using

34 Chapter 6 Help

Django FileBrowser Documentation Release 357

bull Please do NOT add tickets if yoursquore having problems with serving staticmedia-files (because this is not relatedto the FileBrowser)

bull Please do NOT add tickets referring to Djangos trunk version

bull At best add a patch

Note Be aware that we may close issues not following these guidlines without further notifications

613 Translation

Translation is done via Transifex

Supported Languages

see httpswwwtransifexnetprojectspdjango-filebrowserresourcedjangopo

614 FileBrowser 35 Release Notes

FileBrowser 35 is compatible with Django 14151617 as well as Grappelli 242526

Update from FileBrowser 34x

bull Update Django to 14151617 and check httpsdocsdjangoprojectcomendevreleases14 orhttpsdocsdjangoprojectcomendevreleases15 or httpsdocsdjangoprojectcomendevreleases16

bull Update Grappelli to 24x25x26x

bull Update FileBrowser to 35x

62 Changelog

621 358 (not yet released)

622 357 (September 10th 2014)

bull New Compatibility with Django 17 and Grappelli 26x

bull Improved Updated tests because of the new random suffix with get_available_name (django storage)

bull Improved Added an icon in order to mark finished uploads

bull Improved Show resulting filename (eg with suffix converted) after successful upload

bull Fixed Permissions with file upload

bull Fixed Unified json response with _upload_file (no matter if file already exists or not)

623 356 (April 16th 2014)

bull Fixed Displaying pagination correctly with lots of entries

62 Changelog 35

Django FileBrowser Documentation Release 357

624 355 (April 13th 2014)

bull New Added client-side (JavaScript) file extension validation to the AJAX uploader

bull New Added experimental Python 33 support

bull Improved Tests with convertnormalize (removed special chars from test filename)

bull Fixed File selection after using search box (CKEditor)

bull Fixed Removed encoding of file URIs with CKEditor

625 354 (February 21st 2014)

bull Fixed Placeholder functionality (including tests)

bull Fixed Convertnormalize filenames (including tests)

bull Fixed Handling uppercase extensions with browse

626 353 (January 7 2014)

bull New added path_full to FileObject

bull Improved added docx to EXTENSIONS

bull Improved Recommend pillow instead of PIL as a requirement

bull Improved Added additional test cases

bull Improved Updated documentation

bull Improved Consistent use of storage (eg storagelocation storageurl)

bull Improved Removed unnecessary functions (eg url_join url_strip)

bull Improved Moved sort_by_attr to FileListing

bull Improved Regex matches with file versions on browse

bull Improved Using djangoconfurls (with djangoconfurlsdefaults as fallback)

bull Improved Adding CONTRIBUTINGrst

bull Improved Removed static Media inner class with fields

bull Improved Removed search icon with fields (has not being used)

bull Improved Added custom class attributes with filebrowser field

bull Improved Updated translations

bull Fixed fixed exception handling with python 25

bull Fixed fixes dir with SEARCH_TRAVERSE true and version select

bull Fixed Make Django FileUploadHandlers work (also fixed a memory leak)

bull Fixed return correct filename with OVERWRITE_EXISTING

bull Fixed fb_version_generate with FILEBROWSER_VERSIONS_BASEDIR

bull Fixed Table sorting with ascdesc

bull Fixed Added DeprecationWarning for FileObjectdirectory and FileObjectfolder

36 Chapter 6 Help

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

Django FileBrowser Documentation Release 357

22 Chapter 3 Fields amp Widgets

CHAPTER 4

Admin Interface

41 Admin Interface

The main FileBrowser admin application is an extension for the Django admin interface in order to browser yourmedia folder upload and renamedelete files

411 FileBrowser Site

New in version 340

class FileBrowserSite(name=None app_name=rsquofilebrowserrsquo storage=default_storage)Respresents the FileBrowser admin application (similar to Djangorsquos admin site)

Parameters

bull name ndash A name for the site defaults to None

bull app_name ndash Defaults to lsquofilebrowserrsquo

bull storage ndash A custom storage engine defaults to Djangos default storage

Similar to djangocontribadmin you first need to add a filebrowsersite to your admin interface Inyour urlspy import the default FileBrowser site (or your custom site) and add the site to your URL-patterns (beforeany admin-urls)

from filebrowsersites import site

urlpatterns = patterns(url(r^adminurlfilebrowser include(siteurls))

)

Now you are able to browse the location defined with the storage engine associated to your site

from djangocorefilesstorage import DefaultStoragefrom filebrowsersites import FileBrowserSite

Default FileBrowser sitesite = FileBrowserSite(name=filebrowser storage=DefaultStorage())

My Custom FileBrowser sitecustom_site = FileBrowserSite(name=custom_filebrowser storage=DefaultStorage())custom_sitedirectory = custom_uploads

23

Django FileBrowser Documentation Release 357

Note The module variable site from filebrowsersites is the default FileBrowser application

412 Custom Actions

New in version 340

Similar to Djangorsquos admin actions you can define your FileBrowser actions and thus automate the typical tasks ofyour users Registered custom actions are listed in the detail view of a file and a user can select a single action at atime The selected action will then be applied to the file

The default FileBrowser image actions such as ldquoFlip Verticalrdquo or ldquoRotate 90deg Clockwiserdquo are in fact implemented ascustom actions (see the module filebrowseractions)

Writing Your Own Actions

Custom actions are simple functions

def foo(request fileobjects) Do something with the fileobjects

The first parameter is a HttpRequest object (representing the submitted form in which a user selected the action)and the second parameter is a list of FileObjects to which the action should be applied

The list contains exactly one instance of FileObject (representing the file from the detail view) but this may change inthe future as custom actions may become available also in browse views (similar to admin actions applied to a list ofchecked objects)

Registering an Action

In order to make your action visible you need to register it with a FileBrowser site

siteadd_action(foo)

Once registered the action will appear in the detail view of a file You can also give your action a short description

fooshort_description = Do foo with the File

This short description will then appear in the list of available actions If you do not provide a short description thefunction name will be used instead and FileBrowser will replace any underscores in the function name with spaces

Associating Actions with Specific Files

Each custom action can be associated with a specific file type (eg images audio file etc) to which it applies In orderto do that you need to define a predicatefilter function which takes a single argument (FileObject) and returns Trueif your action is applicable to that FileObject Finally you need to register this filter function with your action

fooapplies_to(lambda fileobject fileobjectfiletype == Image)

In the above example foo will appear in the action list only for image files If you do not specify any filter functionfor your action FileBrowser considers the action as applicable to all files

24 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

Messages amp Intermediate Pages

You can provide a feedback to a user about a successful or failed execution of an action by using a message Forexample

from djangocontrib import messages

def desaturate_image(request fileobjects)for f in fileobjects

Desaturate the imagemessagesadd_message(request messagesSUCCESS _(Image s was desaturated) ffilename)

Some actions may require user confirmation (eg in order to prevent accidental and irreversible modification tofiles) In order to that follow the same pattern as with Djangorsquos admin action and return a HttpResponse objectfrom your action Good practice for intermediate pages is to implement a confirm view and have your action returnHttpResponseRedirect

def crop_image(request fileobjects)files = ampf=join([fpath_relative for f in fileobjects])return HttpResponseRedirect(confirmaction=crop_imageampf=s files)

413 File Storages

New in version 340

You have the option to specify which file storage engine a FileBrowser should use to browseuploadmodify yourmedia files This enables you to use a FileBrowser even if your media files are located at some remote system Seealso the Djangorsquos documentation on storages httpsdocsdjangoprojectcomendevtopicsfiles

To associate a FileBrowser site with a particular storage engine set the storage property of a site object

from djangocorefilesstorage import FileSystemStoragesitestorage = FileSystemStorage(location=pathtomediadirectory base_url=media)

For storage classes other than FileSystemStorage (or those that inherit from that class) therersquos more effort involved inproviding a storage object that can be used with FileBrowser See StorageMixin Class

Note Prior FileBrowser 34 the way to specify FileBrowserlsquos MEDIA_ROOT and MEDIA_URL was via settingspyStarting from version 34 those variables are associated with the storage instance and you can set them as illustratedin the above example

Warning For the reason of backward compatibility FileBrowser settings FILEBROWSER_MEDIA_ROOT andFILEBROWSER_MEDIA_URL can still be used to customize FileBrowser as long as yoursquore using the defaultFileBrowserlsquos site without having changed its storage engine In the next major release of FileBrowser thesesettings will be removed

StorageMixin Class

A FileBrowser uses the Djangorsquos Storage class to access media files However the API of the Storageclass does not provide all methods necessary for FileBrowserrsquos functionality A StorageMixin class fromfilebrowserstorage module therefore defines all the additional methods that a FileBrowser requires

isdir(self name)Returns true if name exists and is a directory

41 Admin Interface 25

Django FileBrowser Documentation Release 357

isfile(self name)Returns true if name exists and is a regular file

move(self old_file_name new_file_name allow_overwrite=False)Moves safely a file from one location to another If allow_ovewrite==False and new_file_nameexists raises an exception

makedirs(self name)Creates all missing directories specified by name Analogue to osmkdirs()

414 Views

All views use the staff_member_requird and path_exists decorator in order to check if the server pathactually exists Some views also use the file_exists decorator

bull Browse fb_browse Browse a directory on your server Returns a FileListing

ndash Optional query string args dir o ot q p filter_date filter_type type

bull Create directory fb_createdir Create a new folder on your server

ndash Optional query string args dir

ndash Signals filebrowser_pre_createdir filebrowser_post_createdir

bull Upload fb_upload Multiple upload

ndash Optional query string args dir type

ndash Signals filebrowser_pre_upload filebrowser_post_upload

bull Edit fb_edit Edit a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_rename filebrowser_post_rename

You are able to apply custom actions (see Custom Actions) to the edit-view

bull Confirm delete fb_confirm_delete Confirm the deletion of a file or folder

ndash Required query string args filename

ndash Optional query string args dir

If you try to delete a folder all filesfolders within this folder are listed on this page

bull Delete fb_delete Delete a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_delete filebrowser_post_delete

Warning If you delete a Folder all items within this Folder are being deleted

bull Version fb_version Generate a version of an image as defined with ADMIN_VERSIONS

ndash Required query string args filename

ndash Optional Query string args dir

This is a helper used by the FileBrowseField and TinyMCE for selecting a version

26 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

415 Signals

The FileBrowser sends a couple of different signals Please take a look at the module filebrowsersignals for furtherexplanation on the provided arguments

bull filebrowser_pre_upload Sent before a an Upload starts

bull filebrowser_post_upload Sent after an Upload has finished

bull filebrowser_pre_delete Sent before an Item (File Folder) is deleted

bull filebrowser_post_delete Sent after an Item (File Folder) has been deleted

bull filebrowser_pre_createdir Sent before a new Folder is created

bull filebrowser_post_createdir Sent after a new Folder has been created

bull filebrowser_pre_rename Sent before an Item (File Folder) is renamed

bull filebrowser_post_rename Sent after an Item (File Folder) has been renamed

bull filebrowser_actions_pre_apply Sent before a custom action is applied

bull filebrowser_actions_post_apply Sent after a custom action has been applied

Example for using these Signals

Herersquos a small example for using the above Signals

from filebrowser import signals

def pre_upload_callback(sender kwargs)Receiver function called before an upload startsprint Pre Upload Callbackprint kwargs kwargs

signalsfilebrowser_pre_uploadconnect(pre_upload_callback)

def post_upload_callback(sender kwargs)Receiver function called each time an upload has finishedprint Post Upload Callbackprint kwargs kwargs You can use all attributes available with the FileObject This is just an example print Filesize kwargs[file]filesizeprint Orientation kwargs[file]orientationprint Extension kwargs[file]extension

signalsfilebrowser_post_uploadconnect(post_upload_callback)

41 Admin Interface 27

Django FileBrowser Documentation Release 357

28 Chapter 4 Admin Interface

CHAPTER 5

Image Versions

51 Versions

With the FileBrowser you are able to define different versionssizes for images This enables you to save an originalimage on your server while having different versions of that image to automatically fit your websites grid Versionsare also useful for responsiveadaptive layouts

511 Defining Versions

New in version 340 methods

First you need to know which versionssizes of an image yoursquod like to generate with your website Letrsquos say yoursquoreusing a 12 column grid with 60px for each column and 20px margin (which is a total of 940px) With this grid youcould (for example) define these image versions

FILEBROWSER_VERSIONS_BASEDIR = _versionsFILEBROWSER_VERSIONS =

admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

Use the methods argument if you need to add a filter

def grayscale(im)Convert image to grayscaleif immode = L

im = imconvert(L)return im

FILEBROWSER_VERSIONS = big verbose_name Big (6 col) width 460 height opts methods [grayscale]

)

29

Django FileBrowser Documentation Release 357

512 Versions and the Admin

When using the FileBrowser with the admin interface you need to define ADMIN_VERSIONS andADMIN_THUMBNAIL (see Settings) ADMIN_VERSIONS are available with the admin ie you are able to seethese versions with the image detail view and you are able to select the versions with the FileBrowseField model field

FILEBROWSER_ADMIN_VERSIONS = [thumbnail small medium big large]FILEBROWSER_ADMIN_THUMBNAIL = admin_thumbnail

513 Versions and the Frontend

With your templates you have two different tags to choose from version and version_object With bothtags the version will be generated if it doesnrsquot already exist OR if the original image is newer than the version Inorder to update an image you just overwrite the original image and the versions will be generated automatically (asyou request them within your template)

A Model example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 blank=True null=True)

With your templates use version if you simply need to retrieve the URL or version_object if you need to geta FileObject

lt-- load filebrowser templatetags --gt load fb_versions

lt-- get the url with version --gtltimg src= version blogentryimage medium gt

lt-- get a fileobject with version_object --gt version_object blogentryimage medium as version_medium version_mediumwidth ltimg src= version_medium gt

Templatetag version

RetrievesGenerates a version and returns an URL

version modelfield_name version_prefix

Templatetag version_object

RetrievesGenerates a version and returns a FileObject

version_object modelfield_name version_prefix as variable

Note With both templatetags version_prefix can either be a string or a variable If version_prefix is astring use quotes

30 Chapter 5 Image Versions

Django FileBrowser Documentation Release 357

514 Versions in Views

If you have a FileObject you can generateretrieve a version with

v = objimageversion_generate(version_prefix) returns a FileObject

515 Placeholder

When developing on a locale machine or a development-server you might not have all the images (resp media-files)available that are on your production instance and downloading these files on a regular basis might not be an option

In that case you can use a placeholder instead of a version You just need to define the PLACEHOLDER and overwritethe settings SHOW_PLACEHOLDER andor FORCE_PLACEHOLDER (see Placeholder)

516 Management Commands

fb_version_generateIf you need to generate certain (or all) versions type

python managepy fb_version_generate

fb_version_removeIf you need to generate certain (or all) versions type

python managepy fb_version_generate

Warning Please be very careful with this command

51 Versions 31

Django FileBrowser Documentation Release 357

32 Chapter 5 Image Versions

CHAPTER 6

Help

61 Help

611 FAQ

Why should I use the FileBrowser

If you need your editors or customers to manage files the FileBrowser is an alternative to an FTP-client Moreoveryou are able to define different image versions according to your websites grid Alternatives to the FileBrowser can befound at httpdjangopackagescomgridsgfile-managers

Do I need Grappelli

Grappelli is a requirement for using the FileBrowser There are several filebrowser-no-grappelli repositories (most ofthem on GitHub) but we donrsquot follow the development

I need help

see Troubleshooting

Why are there no fancy effects

The FileBrowser is about managing files We think that you should prepare your files before uploading them to theserver

How do I upload to another server

Use a custom storage engine see httpsdocsdjangoprojectcomen16howtocustom-file-storage

Why do I need image-versions

You need image-versions if your website is based on a grid

33

Django FileBrowser Documentation Release 357

Is the FileBrowser stable

Wersquove developed the FileBrowser for a couple of years and use it with almost all of our clients That said Grappelli isthe more stable and mature application

How can I contribute

Help is very much needed and appreciated Test the FileBrowser and submit feedbackpatches

Who develops the FileBrowser

The FileBrowser is developed and maintained by Patrick Kranzlmuumlller amp Axel Swoboda of vonautomatisch

612 Troubleshooting

Check your setup

Please check if the problem is caused by your setup

bull Read Quick start guide

bull Check if the staticmedia-files are served correctly

bull Make sure you have removed all custom FileBrowser templates from all locations in TEMPLATE_DIRS orcheck that these templates are compatible with the FileBrowser

Run the tests

Start the shell and type

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Check issues

If your setup is fine please check if your problem is a known issue

bull Take a look at all FileBrowser Issues (incuding closed) and search the FileBrowser Google-Group

Add a ticket

If you think yoursquove found a bug please add a ticket

bull Try to describe your problem as precisely as possible

bull Tell us what you did in order to solve the problem

bull Tell us what version of the FileBrowser you are using

bull Tell us what version of Django you are using

34 Chapter 6 Help

Django FileBrowser Documentation Release 357

bull Please do NOT add tickets if yoursquore having problems with serving staticmedia-files (because this is not relatedto the FileBrowser)

bull Please do NOT add tickets referring to Djangos trunk version

bull At best add a patch

Note Be aware that we may close issues not following these guidlines without further notifications

613 Translation

Translation is done via Transifex

Supported Languages

see httpswwwtransifexnetprojectspdjango-filebrowserresourcedjangopo

614 FileBrowser 35 Release Notes

FileBrowser 35 is compatible with Django 14151617 as well as Grappelli 242526

Update from FileBrowser 34x

bull Update Django to 14151617 and check httpsdocsdjangoprojectcomendevreleases14 orhttpsdocsdjangoprojectcomendevreleases15 or httpsdocsdjangoprojectcomendevreleases16

bull Update Grappelli to 24x25x26x

bull Update FileBrowser to 35x

62 Changelog

621 358 (not yet released)

622 357 (September 10th 2014)

bull New Compatibility with Django 17 and Grappelli 26x

bull Improved Updated tests because of the new random suffix with get_available_name (django storage)

bull Improved Added an icon in order to mark finished uploads

bull Improved Show resulting filename (eg with suffix converted) after successful upload

bull Fixed Permissions with file upload

bull Fixed Unified json response with _upload_file (no matter if file already exists or not)

623 356 (April 16th 2014)

bull Fixed Displaying pagination correctly with lots of entries

62 Changelog 35

Django FileBrowser Documentation Release 357

624 355 (April 13th 2014)

bull New Added client-side (JavaScript) file extension validation to the AJAX uploader

bull New Added experimental Python 33 support

bull Improved Tests with convertnormalize (removed special chars from test filename)

bull Fixed File selection after using search box (CKEditor)

bull Fixed Removed encoding of file URIs with CKEditor

625 354 (February 21st 2014)

bull Fixed Placeholder functionality (including tests)

bull Fixed Convertnormalize filenames (including tests)

bull Fixed Handling uppercase extensions with browse

626 353 (January 7 2014)

bull New added path_full to FileObject

bull Improved added docx to EXTENSIONS

bull Improved Recommend pillow instead of PIL as a requirement

bull Improved Added additional test cases

bull Improved Updated documentation

bull Improved Consistent use of storage (eg storagelocation storageurl)

bull Improved Removed unnecessary functions (eg url_join url_strip)

bull Improved Moved sort_by_attr to FileListing

bull Improved Regex matches with file versions on browse

bull Improved Using djangoconfurls (with djangoconfurlsdefaults as fallback)

bull Improved Adding CONTRIBUTINGrst

bull Improved Removed static Media inner class with fields

bull Improved Removed search icon with fields (has not being used)

bull Improved Added custom class attributes with filebrowser field

bull Improved Updated translations

bull Fixed fixed exception handling with python 25

bull Fixed fixes dir with SEARCH_TRAVERSE true and version select

bull Fixed Make Django FileUploadHandlers work (also fixed a memory leak)

bull Fixed return correct filename with OVERWRITE_EXISTING

bull Fixed fb_version_generate with FILEBROWSER_VERSIONS_BASEDIR

bull Fixed Table sorting with ascdesc

bull Fixed Added DeprecationWarning for FileObjectdirectory and FileObjectfolder

36 Chapter 6 Help

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

CHAPTER 4

Admin Interface

41 Admin Interface

The main FileBrowser admin application is an extension for the Django admin interface in order to browser yourmedia folder upload and renamedelete files

411 FileBrowser Site

New in version 340

class FileBrowserSite(name=None app_name=rsquofilebrowserrsquo storage=default_storage)Respresents the FileBrowser admin application (similar to Djangorsquos admin site)

Parameters

bull name ndash A name for the site defaults to None

bull app_name ndash Defaults to lsquofilebrowserrsquo

bull storage ndash A custom storage engine defaults to Djangos default storage

Similar to djangocontribadmin you first need to add a filebrowsersite to your admin interface Inyour urlspy import the default FileBrowser site (or your custom site) and add the site to your URL-patterns (beforeany admin-urls)

from filebrowsersites import site

urlpatterns = patterns(url(r^adminurlfilebrowser include(siteurls))

)

Now you are able to browse the location defined with the storage engine associated to your site

from djangocorefilesstorage import DefaultStoragefrom filebrowsersites import FileBrowserSite

Default FileBrowser sitesite = FileBrowserSite(name=filebrowser storage=DefaultStorage())

My Custom FileBrowser sitecustom_site = FileBrowserSite(name=custom_filebrowser storage=DefaultStorage())custom_sitedirectory = custom_uploads

23

Django FileBrowser Documentation Release 357

Note The module variable site from filebrowsersites is the default FileBrowser application

412 Custom Actions

New in version 340

Similar to Djangorsquos admin actions you can define your FileBrowser actions and thus automate the typical tasks ofyour users Registered custom actions are listed in the detail view of a file and a user can select a single action at atime The selected action will then be applied to the file

The default FileBrowser image actions such as ldquoFlip Verticalrdquo or ldquoRotate 90deg Clockwiserdquo are in fact implemented ascustom actions (see the module filebrowseractions)

Writing Your Own Actions

Custom actions are simple functions

def foo(request fileobjects) Do something with the fileobjects

The first parameter is a HttpRequest object (representing the submitted form in which a user selected the action)and the second parameter is a list of FileObjects to which the action should be applied

The list contains exactly one instance of FileObject (representing the file from the detail view) but this may change inthe future as custom actions may become available also in browse views (similar to admin actions applied to a list ofchecked objects)

Registering an Action

In order to make your action visible you need to register it with a FileBrowser site

siteadd_action(foo)

Once registered the action will appear in the detail view of a file You can also give your action a short description

fooshort_description = Do foo with the File

This short description will then appear in the list of available actions If you do not provide a short description thefunction name will be used instead and FileBrowser will replace any underscores in the function name with spaces

Associating Actions with Specific Files

Each custom action can be associated with a specific file type (eg images audio file etc) to which it applies In orderto do that you need to define a predicatefilter function which takes a single argument (FileObject) and returns Trueif your action is applicable to that FileObject Finally you need to register this filter function with your action

fooapplies_to(lambda fileobject fileobjectfiletype == Image)

In the above example foo will appear in the action list only for image files If you do not specify any filter functionfor your action FileBrowser considers the action as applicable to all files

24 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

Messages amp Intermediate Pages

You can provide a feedback to a user about a successful or failed execution of an action by using a message Forexample

from djangocontrib import messages

def desaturate_image(request fileobjects)for f in fileobjects

Desaturate the imagemessagesadd_message(request messagesSUCCESS _(Image s was desaturated) ffilename)

Some actions may require user confirmation (eg in order to prevent accidental and irreversible modification tofiles) In order to that follow the same pattern as with Djangorsquos admin action and return a HttpResponse objectfrom your action Good practice for intermediate pages is to implement a confirm view and have your action returnHttpResponseRedirect

def crop_image(request fileobjects)files = ampf=join([fpath_relative for f in fileobjects])return HttpResponseRedirect(confirmaction=crop_imageampf=s files)

413 File Storages

New in version 340

You have the option to specify which file storage engine a FileBrowser should use to browseuploadmodify yourmedia files This enables you to use a FileBrowser even if your media files are located at some remote system Seealso the Djangorsquos documentation on storages httpsdocsdjangoprojectcomendevtopicsfiles

To associate a FileBrowser site with a particular storage engine set the storage property of a site object

from djangocorefilesstorage import FileSystemStoragesitestorage = FileSystemStorage(location=pathtomediadirectory base_url=media)

For storage classes other than FileSystemStorage (or those that inherit from that class) therersquos more effort involved inproviding a storage object that can be used with FileBrowser See StorageMixin Class

Note Prior FileBrowser 34 the way to specify FileBrowserlsquos MEDIA_ROOT and MEDIA_URL was via settingspyStarting from version 34 those variables are associated with the storage instance and you can set them as illustratedin the above example

Warning For the reason of backward compatibility FileBrowser settings FILEBROWSER_MEDIA_ROOT andFILEBROWSER_MEDIA_URL can still be used to customize FileBrowser as long as yoursquore using the defaultFileBrowserlsquos site without having changed its storage engine In the next major release of FileBrowser thesesettings will be removed

StorageMixin Class

A FileBrowser uses the Djangorsquos Storage class to access media files However the API of the Storageclass does not provide all methods necessary for FileBrowserrsquos functionality A StorageMixin class fromfilebrowserstorage module therefore defines all the additional methods that a FileBrowser requires

isdir(self name)Returns true if name exists and is a directory

41 Admin Interface 25

Django FileBrowser Documentation Release 357

isfile(self name)Returns true if name exists and is a regular file

move(self old_file_name new_file_name allow_overwrite=False)Moves safely a file from one location to another If allow_ovewrite==False and new_file_nameexists raises an exception

makedirs(self name)Creates all missing directories specified by name Analogue to osmkdirs()

414 Views

All views use the staff_member_requird and path_exists decorator in order to check if the server pathactually exists Some views also use the file_exists decorator

bull Browse fb_browse Browse a directory on your server Returns a FileListing

ndash Optional query string args dir o ot q p filter_date filter_type type

bull Create directory fb_createdir Create a new folder on your server

ndash Optional query string args dir

ndash Signals filebrowser_pre_createdir filebrowser_post_createdir

bull Upload fb_upload Multiple upload

ndash Optional query string args dir type

ndash Signals filebrowser_pre_upload filebrowser_post_upload

bull Edit fb_edit Edit a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_rename filebrowser_post_rename

You are able to apply custom actions (see Custom Actions) to the edit-view

bull Confirm delete fb_confirm_delete Confirm the deletion of a file or folder

ndash Required query string args filename

ndash Optional query string args dir

If you try to delete a folder all filesfolders within this folder are listed on this page

bull Delete fb_delete Delete a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_delete filebrowser_post_delete

Warning If you delete a Folder all items within this Folder are being deleted

bull Version fb_version Generate a version of an image as defined with ADMIN_VERSIONS

ndash Required query string args filename

ndash Optional Query string args dir

This is a helper used by the FileBrowseField and TinyMCE for selecting a version

26 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

415 Signals

The FileBrowser sends a couple of different signals Please take a look at the module filebrowsersignals for furtherexplanation on the provided arguments

bull filebrowser_pre_upload Sent before a an Upload starts

bull filebrowser_post_upload Sent after an Upload has finished

bull filebrowser_pre_delete Sent before an Item (File Folder) is deleted

bull filebrowser_post_delete Sent after an Item (File Folder) has been deleted

bull filebrowser_pre_createdir Sent before a new Folder is created

bull filebrowser_post_createdir Sent after a new Folder has been created

bull filebrowser_pre_rename Sent before an Item (File Folder) is renamed

bull filebrowser_post_rename Sent after an Item (File Folder) has been renamed

bull filebrowser_actions_pre_apply Sent before a custom action is applied

bull filebrowser_actions_post_apply Sent after a custom action has been applied

Example for using these Signals

Herersquos a small example for using the above Signals

from filebrowser import signals

def pre_upload_callback(sender kwargs)Receiver function called before an upload startsprint Pre Upload Callbackprint kwargs kwargs

signalsfilebrowser_pre_uploadconnect(pre_upload_callback)

def post_upload_callback(sender kwargs)Receiver function called each time an upload has finishedprint Post Upload Callbackprint kwargs kwargs You can use all attributes available with the FileObject This is just an example print Filesize kwargs[file]filesizeprint Orientation kwargs[file]orientationprint Extension kwargs[file]extension

signalsfilebrowser_post_uploadconnect(post_upload_callback)

41 Admin Interface 27

Django FileBrowser Documentation Release 357

28 Chapter 4 Admin Interface

CHAPTER 5

Image Versions

51 Versions

With the FileBrowser you are able to define different versionssizes for images This enables you to save an originalimage on your server while having different versions of that image to automatically fit your websites grid Versionsare also useful for responsiveadaptive layouts

511 Defining Versions

New in version 340 methods

First you need to know which versionssizes of an image yoursquod like to generate with your website Letrsquos say yoursquoreusing a 12 column grid with 60px for each column and 20px margin (which is a total of 940px) With this grid youcould (for example) define these image versions

FILEBROWSER_VERSIONS_BASEDIR = _versionsFILEBROWSER_VERSIONS =

admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

Use the methods argument if you need to add a filter

def grayscale(im)Convert image to grayscaleif immode = L

im = imconvert(L)return im

FILEBROWSER_VERSIONS = big verbose_name Big (6 col) width 460 height opts methods [grayscale]

)

29

Django FileBrowser Documentation Release 357

512 Versions and the Admin

When using the FileBrowser with the admin interface you need to define ADMIN_VERSIONS andADMIN_THUMBNAIL (see Settings) ADMIN_VERSIONS are available with the admin ie you are able to seethese versions with the image detail view and you are able to select the versions with the FileBrowseField model field

FILEBROWSER_ADMIN_VERSIONS = [thumbnail small medium big large]FILEBROWSER_ADMIN_THUMBNAIL = admin_thumbnail

513 Versions and the Frontend

With your templates you have two different tags to choose from version and version_object With bothtags the version will be generated if it doesnrsquot already exist OR if the original image is newer than the version Inorder to update an image you just overwrite the original image and the versions will be generated automatically (asyou request them within your template)

A Model example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 blank=True null=True)

With your templates use version if you simply need to retrieve the URL or version_object if you need to geta FileObject

lt-- load filebrowser templatetags --gt load fb_versions

lt-- get the url with version --gtltimg src= version blogentryimage medium gt

lt-- get a fileobject with version_object --gt version_object blogentryimage medium as version_medium version_mediumwidth ltimg src= version_medium gt

Templatetag version

RetrievesGenerates a version and returns an URL

version modelfield_name version_prefix

Templatetag version_object

RetrievesGenerates a version and returns a FileObject

version_object modelfield_name version_prefix as variable

Note With both templatetags version_prefix can either be a string or a variable If version_prefix is astring use quotes

30 Chapter 5 Image Versions

Django FileBrowser Documentation Release 357

514 Versions in Views

If you have a FileObject you can generateretrieve a version with

v = objimageversion_generate(version_prefix) returns a FileObject

515 Placeholder

When developing on a locale machine or a development-server you might not have all the images (resp media-files)available that are on your production instance and downloading these files on a regular basis might not be an option

In that case you can use a placeholder instead of a version You just need to define the PLACEHOLDER and overwritethe settings SHOW_PLACEHOLDER andor FORCE_PLACEHOLDER (see Placeholder)

516 Management Commands

fb_version_generateIf you need to generate certain (or all) versions type

python managepy fb_version_generate

fb_version_removeIf you need to generate certain (or all) versions type

python managepy fb_version_generate

Warning Please be very careful with this command

51 Versions 31

Django FileBrowser Documentation Release 357

32 Chapter 5 Image Versions

CHAPTER 6

Help

61 Help

611 FAQ

Why should I use the FileBrowser

If you need your editors or customers to manage files the FileBrowser is an alternative to an FTP-client Moreoveryou are able to define different image versions according to your websites grid Alternatives to the FileBrowser can befound at httpdjangopackagescomgridsgfile-managers

Do I need Grappelli

Grappelli is a requirement for using the FileBrowser There are several filebrowser-no-grappelli repositories (most ofthem on GitHub) but we donrsquot follow the development

I need help

see Troubleshooting

Why are there no fancy effects

The FileBrowser is about managing files We think that you should prepare your files before uploading them to theserver

How do I upload to another server

Use a custom storage engine see httpsdocsdjangoprojectcomen16howtocustom-file-storage

Why do I need image-versions

You need image-versions if your website is based on a grid

33

Django FileBrowser Documentation Release 357

Is the FileBrowser stable

Wersquove developed the FileBrowser for a couple of years and use it with almost all of our clients That said Grappelli isthe more stable and mature application

How can I contribute

Help is very much needed and appreciated Test the FileBrowser and submit feedbackpatches

Who develops the FileBrowser

The FileBrowser is developed and maintained by Patrick Kranzlmuumlller amp Axel Swoboda of vonautomatisch

612 Troubleshooting

Check your setup

Please check if the problem is caused by your setup

bull Read Quick start guide

bull Check if the staticmedia-files are served correctly

bull Make sure you have removed all custom FileBrowser templates from all locations in TEMPLATE_DIRS orcheck that these templates are compatible with the FileBrowser

Run the tests

Start the shell and type

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Check issues

If your setup is fine please check if your problem is a known issue

bull Take a look at all FileBrowser Issues (incuding closed) and search the FileBrowser Google-Group

Add a ticket

If you think yoursquove found a bug please add a ticket

bull Try to describe your problem as precisely as possible

bull Tell us what you did in order to solve the problem

bull Tell us what version of the FileBrowser you are using

bull Tell us what version of Django you are using

34 Chapter 6 Help

Django FileBrowser Documentation Release 357

bull Please do NOT add tickets if yoursquore having problems with serving staticmedia-files (because this is not relatedto the FileBrowser)

bull Please do NOT add tickets referring to Djangos trunk version

bull At best add a patch

Note Be aware that we may close issues not following these guidlines without further notifications

613 Translation

Translation is done via Transifex

Supported Languages

see httpswwwtransifexnetprojectspdjango-filebrowserresourcedjangopo

614 FileBrowser 35 Release Notes

FileBrowser 35 is compatible with Django 14151617 as well as Grappelli 242526

Update from FileBrowser 34x

bull Update Django to 14151617 and check httpsdocsdjangoprojectcomendevreleases14 orhttpsdocsdjangoprojectcomendevreleases15 or httpsdocsdjangoprojectcomendevreleases16

bull Update Grappelli to 24x25x26x

bull Update FileBrowser to 35x

62 Changelog

621 358 (not yet released)

622 357 (September 10th 2014)

bull New Compatibility with Django 17 and Grappelli 26x

bull Improved Updated tests because of the new random suffix with get_available_name (django storage)

bull Improved Added an icon in order to mark finished uploads

bull Improved Show resulting filename (eg with suffix converted) after successful upload

bull Fixed Permissions with file upload

bull Fixed Unified json response with _upload_file (no matter if file already exists or not)

623 356 (April 16th 2014)

bull Fixed Displaying pagination correctly with lots of entries

62 Changelog 35

Django FileBrowser Documentation Release 357

624 355 (April 13th 2014)

bull New Added client-side (JavaScript) file extension validation to the AJAX uploader

bull New Added experimental Python 33 support

bull Improved Tests with convertnormalize (removed special chars from test filename)

bull Fixed File selection after using search box (CKEditor)

bull Fixed Removed encoding of file URIs with CKEditor

625 354 (February 21st 2014)

bull Fixed Placeholder functionality (including tests)

bull Fixed Convertnormalize filenames (including tests)

bull Fixed Handling uppercase extensions with browse

626 353 (January 7 2014)

bull New added path_full to FileObject

bull Improved added docx to EXTENSIONS

bull Improved Recommend pillow instead of PIL as a requirement

bull Improved Added additional test cases

bull Improved Updated documentation

bull Improved Consistent use of storage (eg storagelocation storageurl)

bull Improved Removed unnecessary functions (eg url_join url_strip)

bull Improved Moved sort_by_attr to FileListing

bull Improved Regex matches with file versions on browse

bull Improved Using djangoconfurls (with djangoconfurlsdefaults as fallback)

bull Improved Adding CONTRIBUTINGrst

bull Improved Removed static Media inner class with fields

bull Improved Removed search icon with fields (has not being used)

bull Improved Added custom class attributes with filebrowser field

bull Improved Updated translations

bull Fixed fixed exception handling with python 25

bull Fixed fixes dir with SEARCH_TRAVERSE true and version select

bull Fixed Make Django FileUploadHandlers work (also fixed a memory leak)

bull Fixed return correct filename with OVERWRITE_EXISTING

bull Fixed fb_version_generate with FILEBROWSER_VERSIONS_BASEDIR

bull Fixed Table sorting with ascdesc

bull Fixed Added DeprecationWarning for FileObjectdirectory and FileObjectfolder

36 Chapter 6 Help

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

Django FileBrowser Documentation Release 357

Note The module variable site from filebrowsersites is the default FileBrowser application

412 Custom Actions

New in version 340

Similar to Djangorsquos admin actions you can define your FileBrowser actions and thus automate the typical tasks ofyour users Registered custom actions are listed in the detail view of a file and a user can select a single action at atime The selected action will then be applied to the file

The default FileBrowser image actions such as ldquoFlip Verticalrdquo or ldquoRotate 90deg Clockwiserdquo are in fact implemented ascustom actions (see the module filebrowseractions)

Writing Your Own Actions

Custom actions are simple functions

def foo(request fileobjects) Do something with the fileobjects

The first parameter is a HttpRequest object (representing the submitted form in which a user selected the action)and the second parameter is a list of FileObjects to which the action should be applied

The list contains exactly one instance of FileObject (representing the file from the detail view) but this may change inthe future as custom actions may become available also in browse views (similar to admin actions applied to a list ofchecked objects)

Registering an Action

In order to make your action visible you need to register it with a FileBrowser site

siteadd_action(foo)

Once registered the action will appear in the detail view of a file You can also give your action a short description

fooshort_description = Do foo with the File

This short description will then appear in the list of available actions If you do not provide a short description thefunction name will be used instead and FileBrowser will replace any underscores in the function name with spaces

Associating Actions with Specific Files

Each custom action can be associated with a specific file type (eg images audio file etc) to which it applies In orderto do that you need to define a predicatefilter function which takes a single argument (FileObject) and returns Trueif your action is applicable to that FileObject Finally you need to register this filter function with your action

fooapplies_to(lambda fileobject fileobjectfiletype == Image)

In the above example foo will appear in the action list only for image files If you do not specify any filter functionfor your action FileBrowser considers the action as applicable to all files

24 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

Messages amp Intermediate Pages

You can provide a feedback to a user about a successful or failed execution of an action by using a message Forexample

from djangocontrib import messages

def desaturate_image(request fileobjects)for f in fileobjects

Desaturate the imagemessagesadd_message(request messagesSUCCESS _(Image s was desaturated) ffilename)

Some actions may require user confirmation (eg in order to prevent accidental and irreversible modification tofiles) In order to that follow the same pattern as with Djangorsquos admin action and return a HttpResponse objectfrom your action Good practice for intermediate pages is to implement a confirm view and have your action returnHttpResponseRedirect

def crop_image(request fileobjects)files = ampf=join([fpath_relative for f in fileobjects])return HttpResponseRedirect(confirmaction=crop_imageampf=s files)

413 File Storages

New in version 340

You have the option to specify which file storage engine a FileBrowser should use to browseuploadmodify yourmedia files This enables you to use a FileBrowser even if your media files are located at some remote system Seealso the Djangorsquos documentation on storages httpsdocsdjangoprojectcomendevtopicsfiles

To associate a FileBrowser site with a particular storage engine set the storage property of a site object

from djangocorefilesstorage import FileSystemStoragesitestorage = FileSystemStorage(location=pathtomediadirectory base_url=media)

For storage classes other than FileSystemStorage (or those that inherit from that class) therersquos more effort involved inproviding a storage object that can be used with FileBrowser See StorageMixin Class

Note Prior FileBrowser 34 the way to specify FileBrowserlsquos MEDIA_ROOT and MEDIA_URL was via settingspyStarting from version 34 those variables are associated with the storage instance and you can set them as illustratedin the above example

Warning For the reason of backward compatibility FileBrowser settings FILEBROWSER_MEDIA_ROOT andFILEBROWSER_MEDIA_URL can still be used to customize FileBrowser as long as yoursquore using the defaultFileBrowserlsquos site without having changed its storage engine In the next major release of FileBrowser thesesettings will be removed

StorageMixin Class

A FileBrowser uses the Djangorsquos Storage class to access media files However the API of the Storageclass does not provide all methods necessary for FileBrowserrsquos functionality A StorageMixin class fromfilebrowserstorage module therefore defines all the additional methods that a FileBrowser requires

isdir(self name)Returns true if name exists and is a directory

41 Admin Interface 25

Django FileBrowser Documentation Release 357

isfile(self name)Returns true if name exists and is a regular file

move(self old_file_name new_file_name allow_overwrite=False)Moves safely a file from one location to another If allow_ovewrite==False and new_file_nameexists raises an exception

makedirs(self name)Creates all missing directories specified by name Analogue to osmkdirs()

414 Views

All views use the staff_member_requird and path_exists decorator in order to check if the server pathactually exists Some views also use the file_exists decorator

bull Browse fb_browse Browse a directory on your server Returns a FileListing

ndash Optional query string args dir o ot q p filter_date filter_type type

bull Create directory fb_createdir Create a new folder on your server

ndash Optional query string args dir

ndash Signals filebrowser_pre_createdir filebrowser_post_createdir

bull Upload fb_upload Multiple upload

ndash Optional query string args dir type

ndash Signals filebrowser_pre_upload filebrowser_post_upload

bull Edit fb_edit Edit a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_rename filebrowser_post_rename

You are able to apply custom actions (see Custom Actions) to the edit-view

bull Confirm delete fb_confirm_delete Confirm the deletion of a file or folder

ndash Required query string args filename

ndash Optional query string args dir

If you try to delete a folder all filesfolders within this folder are listed on this page

bull Delete fb_delete Delete a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_delete filebrowser_post_delete

Warning If you delete a Folder all items within this Folder are being deleted

bull Version fb_version Generate a version of an image as defined with ADMIN_VERSIONS

ndash Required query string args filename

ndash Optional Query string args dir

This is a helper used by the FileBrowseField and TinyMCE for selecting a version

26 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

415 Signals

The FileBrowser sends a couple of different signals Please take a look at the module filebrowsersignals for furtherexplanation on the provided arguments

bull filebrowser_pre_upload Sent before a an Upload starts

bull filebrowser_post_upload Sent after an Upload has finished

bull filebrowser_pre_delete Sent before an Item (File Folder) is deleted

bull filebrowser_post_delete Sent after an Item (File Folder) has been deleted

bull filebrowser_pre_createdir Sent before a new Folder is created

bull filebrowser_post_createdir Sent after a new Folder has been created

bull filebrowser_pre_rename Sent before an Item (File Folder) is renamed

bull filebrowser_post_rename Sent after an Item (File Folder) has been renamed

bull filebrowser_actions_pre_apply Sent before a custom action is applied

bull filebrowser_actions_post_apply Sent after a custom action has been applied

Example for using these Signals

Herersquos a small example for using the above Signals

from filebrowser import signals

def pre_upload_callback(sender kwargs)Receiver function called before an upload startsprint Pre Upload Callbackprint kwargs kwargs

signalsfilebrowser_pre_uploadconnect(pre_upload_callback)

def post_upload_callback(sender kwargs)Receiver function called each time an upload has finishedprint Post Upload Callbackprint kwargs kwargs You can use all attributes available with the FileObject This is just an example print Filesize kwargs[file]filesizeprint Orientation kwargs[file]orientationprint Extension kwargs[file]extension

signalsfilebrowser_post_uploadconnect(post_upload_callback)

41 Admin Interface 27

Django FileBrowser Documentation Release 357

28 Chapter 4 Admin Interface

CHAPTER 5

Image Versions

51 Versions

With the FileBrowser you are able to define different versionssizes for images This enables you to save an originalimage on your server while having different versions of that image to automatically fit your websites grid Versionsare also useful for responsiveadaptive layouts

511 Defining Versions

New in version 340 methods

First you need to know which versionssizes of an image yoursquod like to generate with your website Letrsquos say yoursquoreusing a 12 column grid with 60px for each column and 20px margin (which is a total of 940px) With this grid youcould (for example) define these image versions

FILEBROWSER_VERSIONS_BASEDIR = _versionsFILEBROWSER_VERSIONS =

admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

Use the methods argument if you need to add a filter

def grayscale(im)Convert image to grayscaleif immode = L

im = imconvert(L)return im

FILEBROWSER_VERSIONS = big verbose_name Big (6 col) width 460 height opts methods [grayscale]

)

29

Django FileBrowser Documentation Release 357

512 Versions and the Admin

When using the FileBrowser with the admin interface you need to define ADMIN_VERSIONS andADMIN_THUMBNAIL (see Settings) ADMIN_VERSIONS are available with the admin ie you are able to seethese versions with the image detail view and you are able to select the versions with the FileBrowseField model field

FILEBROWSER_ADMIN_VERSIONS = [thumbnail small medium big large]FILEBROWSER_ADMIN_THUMBNAIL = admin_thumbnail

513 Versions and the Frontend

With your templates you have two different tags to choose from version and version_object With bothtags the version will be generated if it doesnrsquot already exist OR if the original image is newer than the version Inorder to update an image you just overwrite the original image and the versions will be generated automatically (asyou request them within your template)

A Model example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 blank=True null=True)

With your templates use version if you simply need to retrieve the URL or version_object if you need to geta FileObject

lt-- load filebrowser templatetags --gt load fb_versions

lt-- get the url with version --gtltimg src= version blogentryimage medium gt

lt-- get a fileobject with version_object --gt version_object blogentryimage medium as version_medium version_mediumwidth ltimg src= version_medium gt

Templatetag version

RetrievesGenerates a version and returns an URL

version modelfield_name version_prefix

Templatetag version_object

RetrievesGenerates a version and returns a FileObject

version_object modelfield_name version_prefix as variable

Note With both templatetags version_prefix can either be a string or a variable If version_prefix is astring use quotes

30 Chapter 5 Image Versions

Django FileBrowser Documentation Release 357

514 Versions in Views

If you have a FileObject you can generateretrieve a version with

v = objimageversion_generate(version_prefix) returns a FileObject

515 Placeholder

When developing on a locale machine or a development-server you might not have all the images (resp media-files)available that are on your production instance and downloading these files on a regular basis might not be an option

In that case you can use a placeholder instead of a version You just need to define the PLACEHOLDER and overwritethe settings SHOW_PLACEHOLDER andor FORCE_PLACEHOLDER (see Placeholder)

516 Management Commands

fb_version_generateIf you need to generate certain (or all) versions type

python managepy fb_version_generate

fb_version_removeIf you need to generate certain (or all) versions type

python managepy fb_version_generate

Warning Please be very careful with this command

51 Versions 31

Django FileBrowser Documentation Release 357

32 Chapter 5 Image Versions

CHAPTER 6

Help

61 Help

611 FAQ

Why should I use the FileBrowser

If you need your editors or customers to manage files the FileBrowser is an alternative to an FTP-client Moreoveryou are able to define different image versions according to your websites grid Alternatives to the FileBrowser can befound at httpdjangopackagescomgridsgfile-managers

Do I need Grappelli

Grappelli is a requirement for using the FileBrowser There are several filebrowser-no-grappelli repositories (most ofthem on GitHub) but we donrsquot follow the development

I need help

see Troubleshooting

Why are there no fancy effects

The FileBrowser is about managing files We think that you should prepare your files before uploading them to theserver

How do I upload to another server

Use a custom storage engine see httpsdocsdjangoprojectcomen16howtocustom-file-storage

Why do I need image-versions

You need image-versions if your website is based on a grid

33

Django FileBrowser Documentation Release 357

Is the FileBrowser stable

Wersquove developed the FileBrowser for a couple of years and use it with almost all of our clients That said Grappelli isthe more stable and mature application

How can I contribute

Help is very much needed and appreciated Test the FileBrowser and submit feedbackpatches

Who develops the FileBrowser

The FileBrowser is developed and maintained by Patrick Kranzlmuumlller amp Axel Swoboda of vonautomatisch

612 Troubleshooting

Check your setup

Please check if the problem is caused by your setup

bull Read Quick start guide

bull Check if the staticmedia-files are served correctly

bull Make sure you have removed all custom FileBrowser templates from all locations in TEMPLATE_DIRS orcheck that these templates are compatible with the FileBrowser

Run the tests

Start the shell and type

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Check issues

If your setup is fine please check if your problem is a known issue

bull Take a look at all FileBrowser Issues (incuding closed) and search the FileBrowser Google-Group

Add a ticket

If you think yoursquove found a bug please add a ticket

bull Try to describe your problem as precisely as possible

bull Tell us what you did in order to solve the problem

bull Tell us what version of the FileBrowser you are using

bull Tell us what version of Django you are using

34 Chapter 6 Help

Django FileBrowser Documentation Release 357

bull Please do NOT add tickets if yoursquore having problems with serving staticmedia-files (because this is not relatedto the FileBrowser)

bull Please do NOT add tickets referring to Djangos trunk version

bull At best add a patch

Note Be aware that we may close issues not following these guidlines without further notifications

613 Translation

Translation is done via Transifex

Supported Languages

see httpswwwtransifexnetprojectspdjango-filebrowserresourcedjangopo

614 FileBrowser 35 Release Notes

FileBrowser 35 is compatible with Django 14151617 as well as Grappelli 242526

Update from FileBrowser 34x

bull Update Django to 14151617 and check httpsdocsdjangoprojectcomendevreleases14 orhttpsdocsdjangoprojectcomendevreleases15 or httpsdocsdjangoprojectcomendevreleases16

bull Update Grappelli to 24x25x26x

bull Update FileBrowser to 35x

62 Changelog

621 358 (not yet released)

622 357 (September 10th 2014)

bull New Compatibility with Django 17 and Grappelli 26x

bull Improved Updated tests because of the new random suffix with get_available_name (django storage)

bull Improved Added an icon in order to mark finished uploads

bull Improved Show resulting filename (eg with suffix converted) after successful upload

bull Fixed Permissions with file upload

bull Fixed Unified json response with _upload_file (no matter if file already exists or not)

623 356 (April 16th 2014)

bull Fixed Displaying pagination correctly with lots of entries

62 Changelog 35

Django FileBrowser Documentation Release 357

624 355 (April 13th 2014)

bull New Added client-side (JavaScript) file extension validation to the AJAX uploader

bull New Added experimental Python 33 support

bull Improved Tests with convertnormalize (removed special chars from test filename)

bull Fixed File selection after using search box (CKEditor)

bull Fixed Removed encoding of file URIs with CKEditor

625 354 (February 21st 2014)

bull Fixed Placeholder functionality (including tests)

bull Fixed Convertnormalize filenames (including tests)

bull Fixed Handling uppercase extensions with browse

626 353 (January 7 2014)

bull New added path_full to FileObject

bull Improved added docx to EXTENSIONS

bull Improved Recommend pillow instead of PIL as a requirement

bull Improved Added additional test cases

bull Improved Updated documentation

bull Improved Consistent use of storage (eg storagelocation storageurl)

bull Improved Removed unnecessary functions (eg url_join url_strip)

bull Improved Moved sort_by_attr to FileListing

bull Improved Regex matches with file versions on browse

bull Improved Using djangoconfurls (with djangoconfurlsdefaults as fallback)

bull Improved Adding CONTRIBUTINGrst

bull Improved Removed static Media inner class with fields

bull Improved Removed search icon with fields (has not being used)

bull Improved Added custom class attributes with filebrowser field

bull Improved Updated translations

bull Fixed fixed exception handling with python 25

bull Fixed fixes dir with SEARCH_TRAVERSE true and version select

bull Fixed Make Django FileUploadHandlers work (also fixed a memory leak)

bull Fixed return correct filename with OVERWRITE_EXISTING

bull Fixed fb_version_generate with FILEBROWSER_VERSIONS_BASEDIR

bull Fixed Table sorting with ascdesc

bull Fixed Added DeprecationWarning for FileObjectdirectory and FileObjectfolder

36 Chapter 6 Help

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

Django FileBrowser Documentation Release 357

Messages amp Intermediate Pages

You can provide a feedback to a user about a successful or failed execution of an action by using a message Forexample

from djangocontrib import messages

def desaturate_image(request fileobjects)for f in fileobjects

Desaturate the imagemessagesadd_message(request messagesSUCCESS _(Image s was desaturated) ffilename)

Some actions may require user confirmation (eg in order to prevent accidental and irreversible modification tofiles) In order to that follow the same pattern as with Djangorsquos admin action and return a HttpResponse objectfrom your action Good practice for intermediate pages is to implement a confirm view and have your action returnHttpResponseRedirect

def crop_image(request fileobjects)files = ampf=join([fpath_relative for f in fileobjects])return HttpResponseRedirect(confirmaction=crop_imageampf=s files)

413 File Storages

New in version 340

You have the option to specify which file storage engine a FileBrowser should use to browseuploadmodify yourmedia files This enables you to use a FileBrowser even if your media files are located at some remote system Seealso the Djangorsquos documentation on storages httpsdocsdjangoprojectcomendevtopicsfiles

To associate a FileBrowser site with a particular storage engine set the storage property of a site object

from djangocorefilesstorage import FileSystemStoragesitestorage = FileSystemStorage(location=pathtomediadirectory base_url=media)

For storage classes other than FileSystemStorage (or those that inherit from that class) therersquos more effort involved inproviding a storage object that can be used with FileBrowser See StorageMixin Class

Note Prior FileBrowser 34 the way to specify FileBrowserlsquos MEDIA_ROOT and MEDIA_URL was via settingspyStarting from version 34 those variables are associated with the storage instance and you can set them as illustratedin the above example

Warning For the reason of backward compatibility FileBrowser settings FILEBROWSER_MEDIA_ROOT andFILEBROWSER_MEDIA_URL can still be used to customize FileBrowser as long as yoursquore using the defaultFileBrowserlsquos site without having changed its storage engine In the next major release of FileBrowser thesesettings will be removed

StorageMixin Class

A FileBrowser uses the Djangorsquos Storage class to access media files However the API of the Storageclass does not provide all methods necessary for FileBrowserrsquos functionality A StorageMixin class fromfilebrowserstorage module therefore defines all the additional methods that a FileBrowser requires

isdir(self name)Returns true if name exists and is a directory

41 Admin Interface 25

Django FileBrowser Documentation Release 357

isfile(self name)Returns true if name exists and is a regular file

move(self old_file_name new_file_name allow_overwrite=False)Moves safely a file from one location to another If allow_ovewrite==False and new_file_nameexists raises an exception

makedirs(self name)Creates all missing directories specified by name Analogue to osmkdirs()

414 Views

All views use the staff_member_requird and path_exists decorator in order to check if the server pathactually exists Some views also use the file_exists decorator

bull Browse fb_browse Browse a directory on your server Returns a FileListing

ndash Optional query string args dir o ot q p filter_date filter_type type

bull Create directory fb_createdir Create a new folder on your server

ndash Optional query string args dir

ndash Signals filebrowser_pre_createdir filebrowser_post_createdir

bull Upload fb_upload Multiple upload

ndash Optional query string args dir type

ndash Signals filebrowser_pre_upload filebrowser_post_upload

bull Edit fb_edit Edit a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_rename filebrowser_post_rename

You are able to apply custom actions (see Custom Actions) to the edit-view

bull Confirm delete fb_confirm_delete Confirm the deletion of a file or folder

ndash Required query string args filename

ndash Optional query string args dir

If you try to delete a folder all filesfolders within this folder are listed on this page

bull Delete fb_delete Delete a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_delete filebrowser_post_delete

Warning If you delete a Folder all items within this Folder are being deleted

bull Version fb_version Generate a version of an image as defined with ADMIN_VERSIONS

ndash Required query string args filename

ndash Optional Query string args dir

This is a helper used by the FileBrowseField and TinyMCE for selecting a version

26 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

415 Signals

The FileBrowser sends a couple of different signals Please take a look at the module filebrowsersignals for furtherexplanation on the provided arguments

bull filebrowser_pre_upload Sent before a an Upload starts

bull filebrowser_post_upload Sent after an Upload has finished

bull filebrowser_pre_delete Sent before an Item (File Folder) is deleted

bull filebrowser_post_delete Sent after an Item (File Folder) has been deleted

bull filebrowser_pre_createdir Sent before a new Folder is created

bull filebrowser_post_createdir Sent after a new Folder has been created

bull filebrowser_pre_rename Sent before an Item (File Folder) is renamed

bull filebrowser_post_rename Sent after an Item (File Folder) has been renamed

bull filebrowser_actions_pre_apply Sent before a custom action is applied

bull filebrowser_actions_post_apply Sent after a custom action has been applied

Example for using these Signals

Herersquos a small example for using the above Signals

from filebrowser import signals

def pre_upload_callback(sender kwargs)Receiver function called before an upload startsprint Pre Upload Callbackprint kwargs kwargs

signalsfilebrowser_pre_uploadconnect(pre_upload_callback)

def post_upload_callback(sender kwargs)Receiver function called each time an upload has finishedprint Post Upload Callbackprint kwargs kwargs You can use all attributes available with the FileObject This is just an example print Filesize kwargs[file]filesizeprint Orientation kwargs[file]orientationprint Extension kwargs[file]extension

signalsfilebrowser_post_uploadconnect(post_upload_callback)

41 Admin Interface 27

Django FileBrowser Documentation Release 357

28 Chapter 4 Admin Interface

CHAPTER 5

Image Versions

51 Versions

With the FileBrowser you are able to define different versionssizes for images This enables you to save an originalimage on your server while having different versions of that image to automatically fit your websites grid Versionsare also useful for responsiveadaptive layouts

511 Defining Versions

New in version 340 methods

First you need to know which versionssizes of an image yoursquod like to generate with your website Letrsquos say yoursquoreusing a 12 column grid with 60px for each column and 20px margin (which is a total of 940px) With this grid youcould (for example) define these image versions

FILEBROWSER_VERSIONS_BASEDIR = _versionsFILEBROWSER_VERSIONS =

admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

Use the methods argument if you need to add a filter

def grayscale(im)Convert image to grayscaleif immode = L

im = imconvert(L)return im

FILEBROWSER_VERSIONS = big verbose_name Big (6 col) width 460 height opts methods [grayscale]

)

29

Django FileBrowser Documentation Release 357

512 Versions and the Admin

When using the FileBrowser with the admin interface you need to define ADMIN_VERSIONS andADMIN_THUMBNAIL (see Settings) ADMIN_VERSIONS are available with the admin ie you are able to seethese versions with the image detail view and you are able to select the versions with the FileBrowseField model field

FILEBROWSER_ADMIN_VERSIONS = [thumbnail small medium big large]FILEBROWSER_ADMIN_THUMBNAIL = admin_thumbnail

513 Versions and the Frontend

With your templates you have two different tags to choose from version and version_object With bothtags the version will be generated if it doesnrsquot already exist OR if the original image is newer than the version Inorder to update an image you just overwrite the original image and the versions will be generated automatically (asyou request them within your template)

A Model example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 blank=True null=True)

With your templates use version if you simply need to retrieve the URL or version_object if you need to geta FileObject

lt-- load filebrowser templatetags --gt load fb_versions

lt-- get the url with version --gtltimg src= version blogentryimage medium gt

lt-- get a fileobject with version_object --gt version_object blogentryimage medium as version_medium version_mediumwidth ltimg src= version_medium gt

Templatetag version

RetrievesGenerates a version and returns an URL

version modelfield_name version_prefix

Templatetag version_object

RetrievesGenerates a version and returns a FileObject

version_object modelfield_name version_prefix as variable

Note With both templatetags version_prefix can either be a string or a variable If version_prefix is astring use quotes

30 Chapter 5 Image Versions

Django FileBrowser Documentation Release 357

514 Versions in Views

If you have a FileObject you can generateretrieve a version with

v = objimageversion_generate(version_prefix) returns a FileObject

515 Placeholder

When developing on a locale machine or a development-server you might not have all the images (resp media-files)available that are on your production instance and downloading these files on a regular basis might not be an option

In that case you can use a placeholder instead of a version You just need to define the PLACEHOLDER and overwritethe settings SHOW_PLACEHOLDER andor FORCE_PLACEHOLDER (see Placeholder)

516 Management Commands

fb_version_generateIf you need to generate certain (or all) versions type

python managepy fb_version_generate

fb_version_removeIf you need to generate certain (or all) versions type

python managepy fb_version_generate

Warning Please be very careful with this command

51 Versions 31

Django FileBrowser Documentation Release 357

32 Chapter 5 Image Versions

CHAPTER 6

Help

61 Help

611 FAQ

Why should I use the FileBrowser

If you need your editors or customers to manage files the FileBrowser is an alternative to an FTP-client Moreoveryou are able to define different image versions according to your websites grid Alternatives to the FileBrowser can befound at httpdjangopackagescomgridsgfile-managers

Do I need Grappelli

Grappelli is a requirement for using the FileBrowser There are several filebrowser-no-grappelli repositories (most ofthem on GitHub) but we donrsquot follow the development

I need help

see Troubleshooting

Why are there no fancy effects

The FileBrowser is about managing files We think that you should prepare your files before uploading them to theserver

How do I upload to another server

Use a custom storage engine see httpsdocsdjangoprojectcomen16howtocustom-file-storage

Why do I need image-versions

You need image-versions if your website is based on a grid

33

Django FileBrowser Documentation Release 357

Is the FileBrowser stable

Wersquove developed the FileBrowser for a couple of years and use it with almost all of our clients That said Grappelli isthe more stable and mature application

How can I contribute

Help is very much needed and appreciated Test the FileBrowser and submit feedbackpatches

Who develops the FileBrowser

The FileBrowser is developed and maintained by Patrick Kranzlmuumlller amp Axel Swoboda of vonautomatisch

612 Troubleshooting

Check your setup

Please check if the problem is caused by your setup

bull Read Quick start guide

bull Check if the staticmedia-files are served correctly

bull Make sure you have removed all custom FileBrowser templates from all locations in TEMPLATE_DIRS orcheck that these templates are compatible with the FileBrowser

Run the tests

Start the shell and type

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Check issues

If your setup is fine please check if your problem is a known issue

bull Take a look at all FileBrowser Issues (incuding closed) and search the FileBrowser Google-Group

Add a ticket

If you think yoursquove found a bug please add a ticket

bull Try to describe your problem as precisely as possible

bull Tell us what you did in order to solve the problem

bull Tell us what version of the FileBrowser you are using

bull Tell us what version of Django you are using

34 Chapter 6 Help

Django FileBrowser Documentation Release 357

bull Please do NOT add tickets if yoursquore having problems with serving staticmedia-files (because this is not relatedto the FileBrowser)

bull Please do NOT add tickets referring to Djangos trunk version

bull At best add a patch

Note Be aware that we may close issues not following these guidlines without further notifications

613 Translation

Translation is done via Transifex

Supported Languages

see httpswwwtransifexnetprojectspdjango-filebrowserresourcedjangopo

614 FileBrowser 35 Release Notes

FileBrowser 35 is compatible with Django 14151617 as well as Grappelli 242526

Update from FileBrowser 34x

bull Update Django to 14151617 and check httpsdocsdjangoprojectcomendevreleases14 orhttpsdocsdjangoprojectcomendevreleases15 or httpsdocsdjangoprojectcomendevreleases16

bull Update Grappelli to 24x25x26x

bull Update FileBrowser to 35x

62 Changelog

621 358 (not yet released)

622 357 (September 10th 2014)

bull New Compatibility with Django 17 and Grappelli 26x

bull Improved Updated tests because of the new random suffix with get_available_name (django storage)

bull Improved Added an icon in order to mark finished uploads

bull Improved Show resulting filename (eg with suffix converted) after successful upload

bull Fixed Permissions with file upload

bull Fixed Unified json response with _upload_file (no matter if file already exists or not)

623 356 (April 16th 2014)

bull Fixed Displaying pagination correctly with lots of entries

62 Changelog 35

Django FileBrowser Documentation Release 357

624 355 (April 13th 2014)

bull New Added client-side (JavaScript) file extension validation to the AJAX uploader

bull New Added experimental Python 33 support

bull Improved Tests with convertnormalize (removed special chars from test filename)

bull Fixed File selection after using search box (CKEditor)

bull Fixed Removed encoding of file URIs with CKEditor

625 354 (February 21st 2014)

bull Fixed Placeholder functionality (including tests)

bull Fixed Convertnormalize filenames (including tests)

bull Fixed Handling uppercase extensions with browse

626 353 (January 7 2014)

bull New added path_full to FileObject

bull Improved added docx to EXTENSIONS

bull Improved Recommend pillow instead of PIL as a requirement

bull Improved Added additional test cases

bull Improved Updated documentation

bull Improved Consistent use of storage (eg storagelocation storageurl)

bull Improved Removed unnecessary functions (eg url_join url_strip)

bull Improved Moved sort_by_attr to FileListing

bull Improved Regex matches with file versions on browse

bull Improved Using djangoconfurls (with djangoconfurlsdefaults as fallback)

bull Improved Adding CONTRIBUTINGrst

bull Improved Removed static Media inner class with fields

bull Improved Removed search icon with fields (has not being used)

bull Improved Added custom class attributes with filebrowser field

bull Improved Updated translations

bull Fixed fixed exception handling with python 25

bull Fixed fixes dir with SEARCH_TRAVERSE true and version select

bull Fixed Make Django FileUploadHandlers work (also fixed a memory leak)

bull Fixed return correct filename with OVERWRITE_EXISTING

bull Fixed fb_version_generate with FILEBROWSER_VERSIONS_BASEDIR

bull Fixed Table sorting with ascdesc

bull Fixed Added DeprecationWarning for FileObjectdirectory and FileObjectfolder

36 Chapter 6 Help

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

Django FileBrowser Documentation Release 357

isfile(self name)Returns true if name exists and is a regular file

move(self old_file_name new_file_name allow_overwrite=False)Moves safely a file from one location to another If allow_ovewrite==False and new_file_nameexists raises an exception

makedirs(self name)Creates all missing directories specified by name Analogue to osmkdirs()

414 Views

All views use the staff_member_requird and path_exists decorator in order to check if the server pathactually exists Some views also use the file_exists decorator

bull Browse fb_browse Browse a directory on your server Returns a FileListing

ndash Optional query string args dir o ot q p filter_date filter_type type

bull Create directory fb_createdir Create a new folder on your server

ndash Optional query string args dir

ndash Signals filebrowser_pre_createdir filebrowser_post_createdir

bull Upload fb_upload Multiple upload

ndash Optional query string args dir type

ndash Signals filebrowser_pre_upload filebrowser_post_upload

bull Edit fb_edit Edit a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_rename filebrowser_post_rename

You are able to apply custom actions (see Custom Actions) to the edit-view

bull Confirm delete fb_confirm_delete Confirm the deletion of a file or folder

ndash Required query string args filename

ndash Optional query string args dir

If you try to delete a folder all filesfolders within this folder are listed on this page

bull Delete fb_delete Delete a file or folder

ndash Required query string args filename

ndash Optional query string args dir

ndash Signals filebrowser_pre_delete filebrowser_post_delete

Warning If you delete a Folder all items within this Folder are being deleted

bull Version fb_version Generate a version of an image as defined with ADMIN_VERSIONS

ndash Required query string args filename

ndash Optional Query string args dir

This is a helper used by the FileBrowseField and TinyMCE for selecting a version

26 Chapter 4 Admin Interface

Django FileBrowser Documentation Release 357

415 Signals

The FileBrowser sends a couple of different signals Please take a look at the module filebrowsersignals for furtherexplanation on the provided arguments

bull filebrowser_pre_upload Sent before a an Upload starts

bull filebrowser_post_upload Sent after an Upload has finished

bull filebrowser_pre_delete Sent before an Item (File Folder) is deleted

bull filebrowser_post_delete Sent after an Item (File Folder) has been deleted

bull filebrowser_pre_createdir Sent before a new Folder is created

bull filebrowser_post_createdir Sent after a new Folder has been created

bull filebrowser_pre_rename Sent before an Item (File Folder) is renamed

bull filebrowser_post_rename Sent after an Item (File Folder) has been renamed

bull filebrowser_actions_pre_apply Sent before a custom action is applied

bull filebrowser_actions_post_apply Sent after a custom action has been applied

Example for using these Signals

Herersquos a small example for using the above Signals

from filebrowser import signals

def pre_upload_callback(sender kwargs)Receiver function called before an upload startsprint Pre Upload Callbackprint kwargs kwargs

signalsfilebrowser_pre_uploadconnect(pre_upload_callback)

def post_upload_callback(sender kwargs)Receiver function called each time an upload has finishedprint Post Upload Callbackprint kwargs kwargs You can use all attributes available with the FileObject This is just an example print Filesize kwargs[file]filesizeprint Orientation kwargs[file]orientationprint Extension kwargs[file]extension

signalsfilebrowser_post_uploadconnect(post_upload_callback)

41 Admin Interface 27

Django FileBrowser Documentation Release 357

28 Chapter 4 Admin Interface

CHAPTER 5

Image Versions

51 Versions

With the FileBrowser you are able to define different versionssizes for images This enables you to save an originalimage on your server while having different versions of that image to automatically fit your websites grid Versionsare also useful for responsiveadaptive layouts

511 Defining Versions

New in version 340 methods

First you need to know which versionssizes of an image yoursquod like to generate with your website Letrsquos say yoursquoreusing a 12 column grid with 60px for each column and 20px margin (which is a total of 940px) With this grid youcould (for example) define these image versions

FILEBROWSER_VERSIONS_BASEDIR = _versionsFILEBROWSER_VERSIONS =

admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

Use the methods argument if you need to add a filter

def grayscale(im)Convert image to grayscaleif immode = L

im = imconvert(L)return im

FILEBROWSER_VERSIONS = big verbose_name Big (6 col) width 460 height opts methods [grayscale]

)

29

Django FileBrowser Documentation Release 357

512 Versions and the Admin

When using the FileBrowser with the admin interface you need to define ADMIN_VERSIONS andADMIN_THUMBNAIL (see Settings) ADMIN_VERSIONS are available with the admin ie you are able to seethese versions with the image detail view and you are able to select the versions with the FileBrowseField model field

FILEBROWSER_ADMIN_VERSIONS = [thumbnail small medium big large]FILEBROWSER_ADMIN_THUMBNAIL = admin_thumbnail

513 Versions and the Frontend

With your templates you have two different tags to choose from version and version_object With bothtags the version will be generated if it doesnrsquot already exist OR if the original image is newer than the version Inorder to update an image you just overwrite the original image and the versions will be generated automatically (asyou request them within your template)

A Model example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 blank=True null=True)

With your templates use version if you simply need to retrieve the URL or version_object if you need to geta FileObject

lt-- load filebrowser templatetags --gt load fb_versions

lt-- get the url with version --gtltimg src= version blogentryimage medium gt

lt-- get a fileobject with version_object --gt version_object blogentryimage medium as version_medium version_mediumwidth ltimg src= version_medium gt

Templatetag version

RetrievesGenerates a version and returns an URL

version modelfield_name version_prefix

Templatetag version_object

RetrievesGenerates a version and returns a FileObject

version_object modelfield_name version_prefix as variable

Note With both templatetags version_prefix can either be a string or a variable If version_prefix is astring use quotes

30 Chapter 5 Image Versions

Django FileBrowser Documentation Release 357

514 Versions in Views

If you have a FileObject you can generateretrieve a version with

v = objimageversion_generate(version_prefix) returns a FileObject

515 Placeholder

When developing on a locale machine or a development-server you might not have all the images (resp media-files)available that are on your production instance and downloading these files on a regular basis might not be an option

In that case you can use a placeholder instead of a version You just need to define the PLACEHOLDER and overwritethe settings SHOW_PLACEHOLDER andor FORCE_PLACEHOLDER (see Placeholder)

516 Management Commands

fb_version_generateIf you need to generate certain (or all) versions type

python managepy fb_version_generate

fb_version_removeIf you need to generate certain (or all) versions type

python managepy fb_version_generate

Warning Please be very careful with this command

51 Versions 31

Django FileBrowser Documentation Release 357

32 Chapter 5 Image Versions

CHAPTER 6

Help

61 Help

611 FAQ

Why should I use the FileBrowser

If you need your editors or customers to manage files the FileBrowser is an alternative to an FTP-client Moreoveryou are able to define different image versions according to your websites grid Alternatives to the FileBrowser can befound at httpdjangopackagescomgridsgfile-managers

Do I need Grappelli

Grappelli is a requirement for using the FileBrowser There are several filebrowser-no-grappelli repositories (most ofthem on GitHub) but we donrsquot follow the development

I need help

see Troubleshooting

Why are there no fancy effects

The FileBrowser is about managing files We think that you should prepare your files before uploading them to theserver

How do I upload to another server

Use a custom storage engine see httpsdocsdjangoprojectcomen16howtocustom-file-storage

Why do I need image-versions

You need image-versions if your website is based on a grid

33

Django FileBrowser Documentation Release 357

Is the FileBrowser stable

Wersquove developed the FileBrowser for a couple of years and use it with almost all of our clients That said Grappelli isthe more stable and mature application

How can I contribute

Help is very much needed and appreciated Test the FileBrowser and submit feedbackpatches

Who develops the FileBrowser

The FileBrowser is developed and maintained by Patrick Kranzlmuumlller amp Axel Swoboda of vonautomatisch

612 Troubleshooting

Check your setup

Please check if the problem is caused by your setup

bull Read Quick start guide

bull Check if the staticmedia-files are served correctly

bull Make sure you have removed all custom FileBrowser templates from all locations in TEMPLATE_DIRS orcheck that these templates are compatible with the FileBrowser

Run the tests

Start the shell and type

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Check issues

If your setup is fine please check if your problem is a known issue

bull Take a look at all FileBrowser Issues (incuding closed) and search the FileBrowser Google-Group

Add a ticket

If you think yoursquove found a bug please add a ticket

bull Try to describe your problem as precisely as possible

bull Tell us what you did in order to solve the problem

bull Tell us what version of the FileBrowser you are using

bull Tell us what version of Django you are using

34 Chapter 6 Help

Django FileBrowser Documentation Release 357

bull Please do NOT add tickets if yoursquore having problems with serving staticmedia-files (because this is not relatedto the FileBrowser)

bull Please do NOT add tickets referring to Djangos trunk version

bull At best add a patch

Note Be aware that we may close issues not following these guidlines without further notifications

613 Translation

Translation is done via Transifex

Supported Languages

see httpswwwtransifexnetprojectspdjango-filebrowserresourcedjangopo

614 FileBrowser 35 Release Notes

FileBrowser 35 is compatible with Django 14151617 as well as Grappelli 242526

Update from FileBrowser 34x

bull Update Django to 14151617 and check httpsdocsdjangoprojectcomendevreleases14 orhttpsdocsdjangoprojectcomendevreleases15 or httpsdocsdjangoprojectcomendevreleases16

bull Update Grappelli to 24x25x26x

bull Update FileBrowser to 35x

62 Changelog

621 358 (not yet released)

622 357 (September 10th 2014)

bull New Compatibility with Django 17 and Grappelli 26x

bull Improved Updated tests because of the new random suffix with get_available_name (django storage)

bull Improved Added an icon in order to mark finished uploads

bull Improved Show resulting filename (eg with suffix converted) after successful upload

bull Fixed Permissions with file upload

bull Fixed Unified json response with _upload_file (no matter if file already exists or not)

623 356 (April 16th 2014)

bull Fixed Displaying pagination correctly with lots of entries

62 Changelog 35

Django FileBrowser Documentation Release 357

624 355 (April 13th 2014)

bull New Added client-side (JavaScript) file extension validation to the AJAX uploader

bull New Added experimental Python 33 support

bull Improved Tests with convertnormalize (removed special chars from test filename)

bull Fixed File selection after using search box (CKEditor)

bull Fixed Removed encoding of file URIs with CKEditor

625 354 (February 21st 2014)

bull Fixed Placeholder functionality (including tests)

bull Fixed Convertnormalize filenames (including tests)

bull Fixed Handling uppercase extensions with browse

626 353 (January 7 2014)

bull New added path_full to FileObject

bull Improved added docx to EXTENSIONS

bull Improved Recommend pillow instead of PIL as a requirement

bull Improved Added additional test cases

bull Improved Updated documentation

bull Improved Consistent use of storage (eg storagelocation storageurl)

bull Improved Removed unnecessary functions (eg url_join url_strip)

bull Improved Moved sort_by_attr to FileListing

bull Improved Regex matches with file versions on browse

bull Improved Using djangoconfurls (with djangoconfurlsdefaults as fallback)

bull Improved Adding CONTRIBUTINGrst

bull Improved Removed static Media inner class with fields

bull Improved Removed search icon with fields (has not being used)

bull Improved Added custom class attributes with filebrowser field

bull Improved Updated translations

bull Fixed fixed exception handling with python 25

bull Fixed fixes dir with SEARCH_TRAVERSE true and version select

bull Fixed Make Django FileUploadHandlers work (also fixed a memory leak)

bull Fixed return correct filename with OVERWRITE_EXISTING

bull Fixed fb_version_generate with FILEBROWSER_VERSIONS_BASEDIR

bull Fixed Table sorting with ascdesc

bull Fixed Added DeprecationWarning for FileObjectdirectory and FileObjectfolder

36 Chapter 6 Help

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

Django FileBrowser Documentation Release 357

415 Signals

The FileBrowser sends a couple of different signals Please take a look at the module filebrowsersignals for furtherexplanation on the provided arguments

bull filebrowser_pre_upload Sent before a an Upload starts

bull filebrowser_post_upload Sent after an Upload has finished

bull filebrowser_pre_delete Sent before an Item (File Folder) is deleted

bull filebrowser_post_delete Sent after an Item (File Folder) has been deleted

bull filebrowser_pre_createdir Sent before a new Folder is created

bull filebrowser_post_createdir Sent after a new Folder has been created

bull filebrowser_pre_rename Sent before an Item (File Folder) is renamed

bull filebrowser_post_rename Sent after an Item (File Folder) has been renamed

bull filebrowser_actions_pre_apply Sent before a custom action is applied

bull filebrowser_actions_post_apply Sent after a custom action has been applied

Example for using these Signals

Herersquos a small example for using the above Signals

from filebrowser import signals

def pre_upload_callback(sender kwargs)Receiver function called before an upload startsprint Pre Upload Callbackprint kwargs kwargs

signalsfilebrowser_pre_uploadconnect(pre_upload_callback)

def post_upload_callback(sender kwargs)Receiver function called each time an upload has finishedprint Post Upload Callbackprint kwargs kwargs You can use all attributes available with the FileObject This is just an example print Filesize kwargs[file]filesizeprint Orientation kwargs[file]orientationprint Extension kwargs[file]extension

signalsfilebrowser_post_uploadconnect(post_upload_callback)

41 Admin Interface 27

Django FileBrowser Documentation Release 357

28 Chapter 4 Admin Interface

CHAPTER 5

Image Versions

51 Versions

With the FileBrowser you are able to define different versionssizes for images This enables you to save an originalimage on your server while having different versions of that image to automatically fit your websites grid Versionsare also useful for responsiveadaptive layouts

511 Defining Versions

New in version 340 methods

First you need to know which versionssizes of an image yoursquod like to generate with your website Letrsquos say yoursquoreusing a 12 column grid with 60px for each column and 20px margin (which is a total of 940px) With this grid youcould (for example) define these image versions

FILEBROWSER_VERSIONS_BASEDIR = _versionsFILEBROWSER_VERSIONS =

admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

Use the methods argument if you need to add a filter

def grayscale(im)Convert image to grayscaleif immode = L

im = imconvert(L)return im

FILEBROWSER_VERSIONS = big verbose_name Big (6 col) width 460 height opts methods [grayscale]

)

29

Django FileBrowser Documentation Release 357

512 Versions and the Admin

When using the FileBrowser with the admin interface you need to define ADMIN_VERSIONS andADMIN_THUMBNAIL (see Settings) ADMIN_VERSIONS are available with the admin ie you are able to seethese versions with the image detail view and you are able to select the versions with the FileBrowseField model field

FILEBROWSER_ADMIN_VERSIONS = [thumbnail small medium big large]FILEBROWSER_ADMIN_THUMBNAIL = admin_thumbnail

513 Versions and the Frontend

With your templates you have two different tags to choose from version and version_object With bothtags the version will be generated if it doesnrsquot already exist OR if the original image is newer than the version Inorder to update an image you just overwrite the original image and the versions will be generated automatically (asyou request them within your template)

A Model example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 blank=True null=True)

With your templates use version if you simply need to retrieve the URL or version_object if you need to geta FileObject

lt-- load filebrowser templatetags --gt load fb_versions

lt-- get the url with version --gtltimg src= version blogentryimage medium gt

lt-- get a fileobject with version_object --gt version_object blogentryimage medium as version_medium version_mediumwidth ltimg src= version_medium gt

Templatetag version

RetrievesGenerates a version and returns an URL

version modelfield_name version_prefix

Templatetag version_object

RetrievesGenerates a version and returns a FileObject

version_object modelfield_name version_prefix as variable

Note With both templatetags version_prefix can either be a string or a variable If version_prefix is astring use quotes

30 Chapter 5 Image Versions

Django FileBrowser Documentation Release 357

514 Versions in Views

If you have a FileObject you can generateretrieve a version with

v = objimageversion_generate(version_prefix) returns a FileObject

515 Placeholder

When developing on a locale machine or a development-server you might not have all the images (resp media-files)available that are on your production instance and downloading these files on a regular basis might not be an option

In that case you can use a placeholder instead of a version You just need to define the PLACEHOLDER and overwritethe settings SHOW_PLACEHOLDER andor FORCE_PLACEHOLDER (see Placeholder)

516 Management Commands

fb_version_generateIf you need to generate certain (or all) versions type

python managepy fb_version_generate

fb_version_removeIf you need to generate certain (or all) versions type

python managepy fb_version_generate

Warning Please be very careful with this command

51 Versions 31

Django FileBrowser Documentation Release 357

32 Chapter 5 Image Versions

CHAPTER 6

Help

61 Help

611 FAQ

Why should I use the FileBrowser

If you need your editors or customers to manage files the FileBrowser is an alternative to an FTP-client Moreoveryou are able to define different image versions according to your websites grid Alternatives to the FileBrowser can befound at httpdjangopackagescomgridsgfile-managers

Do I need Grappelli

Grappelli is a requirement for using the FileBrowser There are several filebrowser-no-grappelli repositories (most ofthem on GitHub) but we donrsquot follow the development

I need help

see Troubleshooting

Why are there no fancy effects

The FileBrowser is about managing files We think that you should prepare your files before uploading them to theserver

How do I upload to another server

Use a custom storage engine see httpsdocsdjangoprojectcomen16howtocustom-file-storage

Why do I need image-versions

You need image-versions if your website is based on a grid

33

Django FileBrowser Documentation Release 357

Is the FileBrowser stable

Wersquove developed the FileBrowser for a couple of years and use it with almost all of our clients That said Grappelli isthe more stable and mature application

How can I contribute

Help is very much needed and appreciated Test the FileBrowser and submit feedbackpatches

Who develops the FileBrowser

The FileBrowser is developed and maintained by Patrick Kranzlmuumlller amp Axel Swoboda of vonautomatisch

612 Troubleshooting

Check your setup

Please check if the problem is caused by your setup

bull Read Quick start guide

bull Check if the staticmedia-files are served correctly

bull Make sure you have removed all custom FileBrowser templates from all locations in TEMPLATE_DIRS orcheck that these templates are compatible with the FileBrowser

Run the tests

Start the shell and type

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Check issues

If your setup is fine please check if your problem is a known issue

bull Take a look at all FileBrowser Issues (incuding closed) and search the FileBrowser Google-Group

Add a ticket

If you think yoursquove found a bug please add a ticket

bull Try to describe your problem as precisely as possible

bull Tell us what you did in order to solve the problem

bull Tell us what version of the FileBrowser you are using

bull Tell us what version of Django you are using

34 Chapter 6 Help

Django FileBrowser Documentation Release 357

bull Please do NOT add tickets if yoursquore having problems with serving staticmedia-files (because this is not relatedto the FileBrowser)

bull Please do NOT add tickets referring to Djangos trunk version

bull At best add a patch

Note Be aware that we may close issues not following these guidlines without further notifications

613 Translation

Translation is done via Transifex

Supported Languages

see httpswwwtransifexnetprojectspdjango-filebrowserresourcedjangopo

614 FileBrowser 35 Release Notes

FileBrowser 35 is compatible with Django 14151617 as well as Grappelli 242526

Update from FileBrowser 34x

bull Update Django to 14151617 and check httpsdocsdjangoprojectcomendevreleases14 orhttpsdocsdjangoprojectcomendevreleases15 or httpsdocsdjangoprojectcomendevreleases16

bull Update Grappelli to 24x25x26x

bull Update FileBrowser to 35x

62 Changelog

621 358 (not yet released)

622 357 (September 10th 2014)

bull New Compatibility with Django 17 and Grappelli 26x

bull Improved Updated tests because of the new random suffix with get_available_name (django storage)

bull Improved Added an icon in order to mark finished uploads

bull Improved Show resulting filename (eg with suffix converted) after successful upload

bull Fixed Permissions with file upload

bull Fixed Unified json response with _upload_file (no matter if file already exists or not)

623 356 (April 16th 2014)

bull Fixed Displaying pagination correctly with lots of entries

62 Changelog 35

Django FileBrowser Documentation Release 357

624 355 (April 13th 2014)

bull New Added client-side (JavaScript) file extension validation to the AJAX uploader

bull New Added experimental Python 33 support

bull Improved Tests with convertnormalize (removed special chars from test filename)

bull Fixed File selection after using search box (CKEditor)

bull Fixed Removed encoding of file URIs with CKEditor

625 354 (February 21st 2014)

bull Fixed Placeholder functionality (including tests)

bull Fixed Convertnormalize filenames (including tests)

bull Fixed Handling uppercase extensions with browse

626 353 (January 7 2014)

bull New added path_full to FileObject

bull Improved added docx to EXTENSIONS

bull Improved Recommend pillow instead of PIL as a requirement

bull Improved Added additional test cases

bull Improved Updated documentation

bull Improved Consistent use of storage (eg storagelocation storageurl)

bull Improved Removed unnecessary functions (eg url_join url_strip)

bull Improved Moved sort_by_attr to FileListing

bull Improved Regex matches with file versions on browse

bull Improved Using djangoconfurls (with djangoconfurlsdefaults as fallback)

bull Improved Adding CONTRIBUTINGrst

bull Improved Removed static Media inner class with fields

bull Improved Removed search icon with fields (has not being used)

bull Improved Added custom class attributes with filebrowser field

bull Improved Updated translations

bull Fixed fixed exception handling with python 25

bull Fixed fixes dir with SEARCH_TRAVERSE true and version select

bull Fixed Make Django FileUploadHandlers work (also fixed a memory leak)

bull Fixed return correct filename with OVERWRITE_EXISTING

bull Fixed fb_version_generate with FILEBROWSER_VERSIONS_BASEDIR

bull Fixed Table sorting with ascdesc

bull Fixed Added DeprecationWarning for FileObjectdirectory and FileObjectfolder

36 Chapter 6 Help

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

Django FileBrowser Documentation Release 357

28 Chapter 4 Admin Interface

CHAPTER 5

Image Versions

51 Versions

With the FileBrowser you are able to define different versionssizes for images This enables you to save an originalimage on your server while having different versions of that image to automatically fit your websites grid Versionsare also useful for responsiveadaptive layouts

511 Defining Versions

New in version 340 methods

First you need to know which versionssizes of an image yoursquod like to generate with your website Letrsquos say yoursquoreusing a 12 column grid with 60px for each column and 20px margin (which is a total of 940px) With this grid youcould (for example) define these image versions

FILEBROWSER_VERSIONS_BASEDIR = _versionsFILEBROWSER_VERSIONS =

admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

Use the methods argument if you need to add a filter

def grayscale(im)Convert image to grayscaleif immode = L

im = imconvert(L)return im

FILEBROWSER_VERSIONS = big verbose_name Big (6 col) width 460 height opts methods [grayscale]

)

29

Django FileBrowser Documentation Release 357

512 Versions and the Admin

When using the FileBrowser with the admin interface you need to define ADMIN_VERSIONS andADMIN_THUMBNAIL (see Settings) ADMIN_VERSIONS are available with the admin ie you are able to seethese versions with the image detail view and you are able to select the versions with the FileBrowseField model field

FILEBROWSER_ADMIN_VERSIONS = [thumbnail small medium big large]FILEBROWSER_ADMIN_THUMBNAIL = admin_thumbnail

513 Versions and the Frontend

With your templates you have two different tags to choose from version and version_object With bothtags the version will be generated if it doesnrsquot already exist OR if the original image is newer than the version Inorder to update an image you just overwrite the original image and the versions will be generated automatically (asyou request them within your template)

A Model example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 blank=True null=True)

With your templates use version if you simply need to retrieve the URL or version_object if you need to geta FileObject

lt-- load filebrowser templatetags --gt load fb_versions

lt-- get the url with version --gtltimg src= version blogentryimage medium gt

lt-- get a fileobject with version_object --gt version_object blogentryimage medium as version_medium version_mediumwidth ltimg src= version_medium gt

Templatetag version

RetrievesGenerates a version and returns an URL

version modelfield_name version_prefix

Templatetag version_object

RetrievesGenerates a version and returns a FileObject

version_object modelfield_name version_prefix as variable

Note With both templatetags version_prefix can either be a string or a variable If version_prefix is astring use quotes

30 Chapter 5 Image Versions

Django FileBrowser Documentation Release 357

514 Versions in Views

If you have a FileObject you can generateretrieve a version with

v = objimageversion_generate(version_prefix) returns a FileObject

515 Placeholder

When developing on a locale machine or a development-server you might not have all the images (resp media-files)available that are on your production instance and downloading these files on a regular basis might not be an option

In that case you can use a placeholder instead of a version You just need to define the PLACEHOLDER and overwritethe settings SHOW_PLACEHOLDER andor FORCE_PLACEHOLDER (see Placeholder)

516 Management Commands

fb_version_generateIf you need to generate certain (or all) versions type

python managepy fb_version_generate

fb_version_removeIf you need to generate certain (or all) versions type

python managepy fb_version_generate

Warning Please be very careful with this command

51 Versions 31

Django FileBrowser Documentation Release 357

32 Chapter 5 Image Versions

CHAPTER 6

Help

61 Help

611 FAQ

Why should I use the FileBrowser

If you need your editors or customers to manage files the FileBrowser is an alternative to an FTP-client Moreoveryou are able to define different image versions according to your websites grid Alternatives to the FileBrowser can befound at httpdjangopackagescomgridsgfile-managers

Do I need Grappelli

Grappelli is a requirement for using the FileBrowser There are several filebrowser-no-grappelli repositories (most ofthem on GitHub) but we donrsquot follow the development

I need help

see Troubleshooting

Why are there no fancy effects

The FileBrowser is about managing files We think that you should prepare your files before uploading them to theserver

How do I upload to another server

Use a custom storage engine see httpsdocsdjangoprojectcomen16howtocustom-file-storage

Why do I need image-versions

You need image-versions if your website is based on a grid

33

Django FileBrowser Documentation Release 357

Is the FileBrowser stable

Wersquove developed the FileBrowser for a couple of years and use it with almost all of our clients That said Grappelli isthe more stable and mature application

How can I contribute

Help is very much needed and appreciated Test the FileBrowser and submit feedbackpatches

Who develops the FileBrowser

The FileBrowser is developed and maintained by Patrick Kranzlmuumlller amp Axel Swoboda of vonautomatisch

612 Troubleshooting

Check your setup

Please check if the problem is caused by your setup

bull Read Quick start guide

bull Check if the staticmedia-files are served correctly

bull Make sure you have removed all custom FileBrowser templates from all locations in TEMPLATE_DIRS orcheck that these templates are compatible with the FileBrowser

Run the tests

Start the shell and type

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Check issues

If your setup is fine please check if your problem is a known issue

bull Take a look at all FileBrowser Issues (incuding closed) and search the FileBrowser Google-Group

Add a ticket

If you think yoursquove found a bug please add a ticket

bull Try to describe your problem as precisely as possible

bull Tell us what you did in order to solve the problem

bull Tell us what version of the FileBrowser you are using

bull Tell us what version of Django you are using

34 Chapter 6 Help

Django FileBrowser Documentation Release 357

bull Please do NOT add tickets if yoursquore having problems with serving staticmedia-files (because this is not relatedto the FileBrowser)

bull Please do NOT add tickets referring to Djangos trunk version

bull At best add a patch

Note Be aware that we may close issues not following these guidlines without further notifications

613 Translation

Translation is done via Transifex

Supported Languages

see httpswwwtransifexnetprojectspdjango-filebrowserresourcedjangopo

614 FileBrowser 35 Release Notes

FileBrowser 35 is compatible with Django 14151617 as well as Grappelli 242526

Update from FileBrowser 34x

bull Update Django to 14151617 and check httpsdocsdjangoprojectcomendevreleases14 orhttpsdocsdjangoprojectcomendevreleases15 or httpsdocsdjangoprojectcomendevreleases16

bull Update Grappelli to 24x25x26x

bull Update FileBrowser to 35x

62 Changelog

621 358 (not yet released)

622 357 (September 10th 2014)

bull New Compatibility with Django 17 and Grappelli 26x

bull Improved Updated tests because of the new random suffix with get_available_name (django storage)

bull Improved Added an icon in order to mark finished uploads

bull Improved Show resulting filename (eg with suffix converted) after successful upload

bull Fixed Permissions with file upload

bull Fixed Unified json response with _upload_file (no matter if file already exists or not)

623 356 (April 16th 2014)

bull Fixed Displaying pagination correctly with lots of entries

62 Changelog 35

Django FileBrowser Documentation Release 357

624 355 (April 13th 2014)

bull New Added client-side (JavaScript) file extension validation to the AJAX uploader

bull New Added experimental Python 33 support

bull Improved Tests with convertnormalize (removed special chars from test filename)

bull Fixed File selection after using search box (CKEditor)

bull Fixed Removed encoding of file URIs with CKEditor

625 354 (February 21st 2014)

bull Fixed Placeholder functionality (including tests)

bull Fixed Convertnormalize filenames (including tests)

bull Fixed Handling uppercase extensions with browse

626 353 (January 7 2014)

bull New added path_full to FileObject

bull Improved added docx to EXTENSIONS

bull Improved Recommend pillow instead of PIL as a requirement

bull Improved Added additional test cases

bull Improved Updated documentation

bull Improved Consistent use of storage (eg storagelocation storageurl)

bull Improved Removed unnecessary functions (eg url_join url_strip)

bull Improved Moved sort_by_attr to FileListing

bull Improved Regex matches with file versions on browse

bull Improved Using djangoconfurls (with djangoconfurlsdefaults as fallback)

bull Improved Adding CONTRIBUTINGrst

bull Improved Removed static Media inner class with fields

bull Improved Removed search icon with fields (has not being used)

bull Improved Added custom class attributes with filebrowser field

bull Improved Updated translations

bull Fixed fixed exception handling with python 25

bull Fixed fixes dir with SEARCH_TRAVERSE true and version select

bull Fixed Make Django FileUploadHandlers work (also fixed a memory leak)

bull Fixed return correct filename with OVERWRITE_EXISTING

bull Fixed fb_version_generate with FILEBROWSER_VERSIONS_BASEDIR

bull Fixed Table sorting with ascdesc

bull Fixed Added DeprecationWarning for FileObjectdirectory and FileObjectfolder

36 Chapter 6 Help

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

CHAPTER 5

Image Versions

51 Versions

With the FileBrowser you are able to define different versionssizes for images This enables you to save an originalimage on your server while having different versions of that image to automatically fit your websites grid Versionsare also useful for responsiveadaptive layouts

511 Defining Versions

New in version 340 methods

First you need to know which versionssizes of an image yoursquod like to generate with your website Letrsquos say yoursquoreusing a 12 column grid with 60px for each column and 20px margin (which is a total of 940px) With this grid youcould (for example) define these image versions

FILEBROWSER_VERSIONS_BASEDIR = _versionsFILEBROWSER_VERSIONS =

admin_thumbnail verbose_name Admin Thumbnail width 60 height 60 opts cropthumbnail verbose_name Thumbnail (1 col) width 60 height 60 opts cropsmall verbose_name Small (2 col) width 140 height opts medium verbose_name Medium (4col ) width 300 height opts big verbose_name Big (6 col) width 460 height opts large verbose_name Large (8 col) width 680 height opts

Use the methods argument if you need to add a filter

def grayscale(im)Convert image to grayscaleif immode = L

im = imconvert(L)return im

FILEBROWSER_VERSIONS = big verbose_name Big (6 col) width 460 height opts methods [grayscale]

)

29

Django FileBrowser Documentation Release 357

512 Versions and the Admin

When using the FileBrowser with the admin interface you need to define ADMIN_VERSIONS andADMIN_THUMBNAIL (see Settings) ADMIN_VERSIONS are available with the admin ie you are able to seethese versions with the image detail view and you are able to select the versions with the FileBrowseField model field

FILEBROWSER_ADMIN_VERSIONS = [thumbnail small medium big large]FILEBROWSER_ADMIN_THUMBNAIL = admin_thumbnail

513 Versions and the Frontend

With your templates you have two different tags to choose from version and version_object With bothtags the version will be generated if it doesnrsquot already exist OR if the original image is newer than the version Inorder to update an image you just overwrite the original image and the versions will be generated automatically (asyou request them within your template)

A Model example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 blank=True null=True)

With your templates use version if you simply need to retrieve the URL or version_object if you need to geta FileObject

lt-- load filebrowser templatetags --gt load fb_versions

lt-- get the url with version --gtltimg src= version blogentryimage medium gt

lt-- get a fileobject with version_object --gt version_object blogentryimage medium as version_medium version_mediumwidth ltimg src= version_medium gt

Templatetag version

RetrievesGenerates a version and returns an URL

version modelfield_name version_prefix

Templatetag version_object

RetrievesGenerates a version and returns a FileObject

version_object modelfield_name version_prefix as variable

Note With both templatetags version_prefix can either be a string or a variable If version_prefix is astring use quotes

30 Chapter 5 Image Versions

Django FileBrowser Documentation Release 357

514 Versions in Views

If you have a FileObject you can generateretrieve a version with

v = objimageversion_generate(version_prefix) returns a FileObject

515 Placeholder

When developing on a locale machine or a development-server you might not have all the images (resp media-files)available that are on your production instance and downloading these files on a regular basis might not be an option

In that case you can use a placeholder instead of a version You just need to define the PLACEHOLDER and overwritethe settings SHOW_PLACEHOLDER andor FORCE_PLACEHOLDER (see Placeholder)

516 Management Commands

fb_version_generateIf you need to generate certain (or all) versions type

python managepy fb_version_generate

fb_version_removeIf you need to generate certain (or all) versions type

python managepy fb_version_generate

Warning Please be very careful with this command

51 Versions 31

Django FileBrowser Documentation Release 357

32 Chapter 5 Image Versions

CHAPTER 6

Help

61 Help

611 FAQ

Why should I use the FileBrowser

If you need your editors or customers to manage files the FileBrowser is an alternative to an FTP-client Moreoveryou are able to define different image versions according to your websites grid Alternatives to the FileBrowser can befound at httpdjangopackagescomgridsgfile-managers

Do I need Grappelli

Grappelli is a requirement for using the FileBrowser There are several filebrowser-no-grappelli repositories (most ofthem on GitHub) but we donrsquot follow the development

I need help

see Troubleshooting

Why are there no fancy effects

The FileBrowser is about managing files We think that you should prepare your files before uploading them to theserver

How do I upload to another server

Use a custom storage engine see httpsdocsdjangoprojectcomen16howtocustom-file-storage

Why do I need image-versions

You need image-versions if your website is based on a grid

33

Django FileBrowser Documentation Release 357

Is the FileBrowser stable

Wersquove developed the FileBrowser for a couple of years and use it with almost all of our clients That said Grappelli isthe more stable and mature application

How can I contribute

Help is very much needed and appreciated Test the FileBrowser and submit feedbackpatches

Who develops the FileBrowser

The FileBrowser is developed and maintained by Patrick Kranzlmuumlller amp Axel Swoboda of vonautomatisch

612 Troubleshooting

Check your setup

Please check if the problem is caused by your setup

bull Read Quick start guide

bull Check if the staticmedia-files are served correctly

bull Make sure you have removed all custom FileBrowser templates from all locations in TEMPLATE_DIRS orcheck that these templates are compatible with the FileBrowser

Run the tests

Start the shell and type

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Check issues

If your setup is fine please check if your problem is a known issue

bull Take a look at all FileBrowser Issues (incuding closed) and search the FileBrowser Google-Group

Add a ticket

If you think yoursquove found a bug please add a ticket

bull Try to describe your problem as precisely as possible

bull Tell us what you did in order to solve the problem

bull Tell us what version of the FileBrowser you are using

bull Tell us what version of Django you are using

34 Chapter 6 Help

Django FileBrowser Documentation Release 357

bull Please do NOT add tickets if yoursquore having problems with serving staticmedia-files (because this is not relatedto the FileBrowser)

bull Please do NOT add tickets referring to Djangos trunk version

bull At best add a patch

Note Be aware that we may close issues not following these guidlines without further notifications

613 Translation

Translation is done via Transifex

Supported Languages

see httpswwwtransifexnetprojectspdjango-filebrowserresourcedjangopo

614 FileBrowser 35 Release Notes

FileBrowser 35 is compatible with Django 14151617 as well as Grappelli 242526

Update from FileBrowser 34x

bull Update Django to 14151617 and check httpsdocsdjangoprojectcomendevreleases14 orhttpsdocsdjangoprojectcomendevreleases15 or httpsdocsdjangoprojectcomendevreleases16

bull Update Grappelli to 24x25x26x

bull Update FileBrowser to 35x

62 Changelog

621 358 (not yet released)

622 357 (September 10th 2014)

bull New Compatibility with Django 17 and Grappelli 26x

bull Improved Updated tests because of the new random suffix with get_available_name (django storage)

bull Improved Added an icon in order to mark finished uploads

bull Improved Show resulting filename (eg with suffix converted) after successful upload

bull Fixed Permissions with file upload

bull Fixed Unified json response with _upload_file (no matter if file already exists or not)

623 356 (April 16th 2014)

bull Fixed Displaying pagination correctly with lots of entries

62 Changelog 35

Django FileBrowser Documentation Release 357

624 355 (April 13th 2014)

bull New Added client-side (JavaScript) file extension validation to the AJAX uploader

bull New Added experimental Python 33 support

bull Improved Tests with convertnormalize (removed special chars from test filename)

bull Fixed File selection after using search box (CKEditor)

bull Fixed Removed encoding of file URIs with CKEditor

625 354 (February 21st 2014)

bull Fixed Placeholder functionality (including tests)

bull Fixed Convertnormalize filenames (including tests)

bull Fixed Handling uppercase extensions with browse

626 353 (January 7 2014)

bull New added path_full to FileObject

bull Improved added docx to EXTENSIONS

bull Improved Recommend pillow instead of PIL as a requirement

bull Improved Added additional test cases

bull Improved Updated documentation

bull Improved Consistent use of storage (eg storagelocation storageurl)

bull Improved Removed unnecessary functions (eg url_join url_strip)

bull Improved Moved sort_by_attr to FileListing

bull Improved Regex matches with file versions on browse

bull Improved Using djangoconfurls (with djangoconfurlsdefaults as fallback)

bull Improved Adding CONTRIBUTINGrst

bull Improved Removed static Media inner class with fields

bull Improved Removed search icon with fields (has not being used)

bull Improved Added custom class attributes with filebrowser field

bull Improved Updated translations

bull Fixed fixed exception handling with python 25

bull Fixed fixes dir with SEARCH_TRAVERSE true and version select

bull Fixed Make Django FileUploadHandlers work (also fixed a memory leak)

bull Fixed return correct filename with OVERWRITE_EXISTING

bull Fixed fb_version_generate with FILEBROWSER_VERSIONS_BASEDIR

bull Fixed Table sorting with ascdesc

bull Fixed Added DeprecationWarning for FileObjectdirectory and FileObjectfolder

36 Chapter 6 Help

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

Django FileBrowser Documentation Release 357

512 Versions and the Admin

When using the FileBrowser with the admin interface you need to define ADMIN_VERSIONS andADMIN_THUMBNAIL (see Settings) ADMIN_VERSIONS are available with the admin ie you are able to seethese versions with the image detail view and you are able to select the versions with the FileBrowseField model field

FILEBROWSER_ADMIN_VERSIONS = [thumbnail small medium big large]FILEBROWSER_ADMIN_THUMBNAIL = admin_thumbnail

513 Versions and the Frontend

With your templates you have two different tags to choose from version and version_object With bothtags the version will be generated if it doesnrsquot already exist OR if the original image is newer than the version Inorder to update an image you just overwrite the original image and the versions will be generated automatically (asyou request them within your template)

A Model example

from filebrowserfields import FileBrowseField

class BlogEntry(modelsModel)image = FileBrowseField(Image max_length=200 blank=True null=True)

With your templates use version if you simply need to retrieve the URL or version_object if you need to geta FileObject

lt-- load filebrowser templatetags --gt load fb_versions

lt-- get the url with version --gtltimg src= version blogentryimage medium gt

lt-- get a fileobject with version_object --gt version_object blogentryimage medium as version_medium version_mediumwidth ltimg src= version_medium gt

Templatetag version

RetrievesGenerates a version and returns an URL

version modelfield_name version_prefix

Templatetag version_object

RetrievesGenerates a version and returns a FileObject

version_object modelfield_name version_prefix as variable

Note With both templatetags version_prefix can either be a string or a variable If version_prefix is astring use quotes

30 Chapter 5 Image Versions

Django FileBrowser Documentation Release 357

514 Versions in Views

If you have a FileObject you can generateretrieve a version with

v = objimageversion_generate(version_prefix) returns a FileObject

515 Placeholder

When developing on a locale machine or a development-server you might not have all the images (resp media-files)available that are on your production instance and downloading these files on a regular basis might not be an option

In that case you can use a placeholder instead of a version You just need to define the PLACEHOLDER and overwritethe settings SHOW_PLACEHOLDER andor FORCE_PLACEHOLDER (see Placeholder)

516 Management Commands

fb_version_generateIf you need to generate certain (or all) versions type

python managepy fb_version_generate

fb_version_removeIf you need to generate certain (or all) versions type

python managepy fb_version_generate

Warning Please be very careful with this command

51 Versions 31

Django FileBrowser Documentation Release 357

32 Chapter 5 Image Versions

CHAPTER 6

Help

61 Help

611 FAQ

Why should I use the FileBrowser

If you need your editors or customers to manage files the FileBrowser is an alternative to an FTP-client Moreoveryou are able to define different image versions according to your websites grid Alternatives to the FileBrowser can befound at httpdjangopackagescomgridsgfile-managers

Do I need Grappelli

Grappelli is a requirement for using the FileBrowser There are several filebrowser-no-grappelli repositories (most ofthem on GitHub) but we donrsquot follow the development

I need help

see Troubleshooting

Why are there no fancy effects

The FileBrowser is about managing files We think that you should prepare your files before uploading them to theserver

How do I upload to another server

Use a custom storage engine see httpsdocsdjangoprojectcomen16howtocustom-file-storage

Why do I need image-versions

You need image-versions if your website is based on a grid

33

Django FileBrowser Documentation Release 357

Is the FileBrowser stable

Wersquove developed the FileBrowser for a couple of years and use it with almost all of our clients That said Grappelli isthe more stable and mature application

How can I contribute

Help is very much needed and appreciated Test the FileBrowser and submit feedbackpatches

Who develops the FileBrowser

The FileBrowser is developed and maintained by Patrick Kranzlmuumlller amp Axel Swoboda of vonautomatisch

612 Troubleshooting

Check your setup

Please check if the problem is caused by your setup

bull Read Quick start guide

bull Check if the staticmedia-files are served correctly

bull Make sure you have removed all custom FileBrowser templates from all locations in TEMPLATE_DIRS orcheck that these templates are compatible with the FileBrowser

Run the tests

Start the shell and type

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Check issues

If your setup is fine please check if your problem is a known issue

bull Take a look at all FileBrowser Issues (incuding closed) and search the FileBrowser Google-Group

Add a ticket

If you think yoursquove found a bug please add a ticket

bull Try to describe your problem as precisely as possible

bull Tell us what you did in order to solve the problem

bull Tell us what version of the FileBrowser you are using

bull Tell us what version of Django you are using

34 Chapter 6 Help

Django FileBrowser Documentation Release 357

bull Please do NOT add tickets if yoursquore having problems with serving staticmedia-files (because this is not relatedto the FileBrowser)

bull Please do NOT add tickets referring to Djangos trunk version

bull At best add a patch

Note Be aware that we may close issues not following these guidlines without further notifications

613 Translation

Translation is done via Transifex

Supported Languages

see httpswwwtransifexnetprojectspdjango-filebrowserresourcedjangopo

614 FileBrowser 35 Release Notes

FileBrowser 35 is compatible with Django 14151617 as well as Grappelli 242526

Update from FileBrowser 34x

bull Update Django to 14151617 and check httpsdocsdjangoprojectcomendevreleases14 orhttpsdocsdjangoprojectcomendevreleases15 or httpsdocsdjangoprojectcomendevreleases16

bull Update Grappelli to 24x25x26x

bull Update FileBrowser to 35x

62 Changelog

621 358 (not yet released)

622 357 (September 10th 2014)

bull New Compatibility with Django 17 and Grappelli 26x

bull Improved Updated tests because of the new random suffix with get_available_name (django storage)

bull Improved Added an icon in order to mark finished uploads

bull Improved Show resulting filename (eg with suffix converted) after successful upload

bull Fixed Permissions with file upload

bull Fixed Unified json response with _upload_file (no matter if file already exists or not)

623 356 (April 16th 2014)

bull Fixed Displaying pagination correctly with lots of entries

62 Changelog 35

Django FileBrowser Documentation Release 357

624 355 (April 13th 2014)

bull New Added client-side (JavaScript) file extension validation to the AJAX uploader

bull New Added experimental Python 33 support

bull Improved Tests with convertnormalize (removed special chars from test filename)

bull Fixed File selection after using search box (CKEditor)

bull Fixed Removed encoding of file URIs with CKEditor

625 354 (February 21st 2014)

bull Fixed Placeholder functionality (including tests)

bull Fixed Convertnormalize filenames (including tests)

bull Fixed Handling uppercase extensions with browse

626 353 (January 7 2014)

bull New added path_full to FileObject

bull Improved added docx to EXTENSIONS

bull Improved Recommend pillow instead of PIL as a requirement

bull Improved Added additional test cases

bull Improved Updated documentation

bull Improved Consistent use of storage (eg storagelocation storageurl)

bull Improved Removed unnecessary functions (eg url_join url_strip)

bull Improved Moved sort_by_attr to FileListing

bull Improved Regex matches with file versions on browse

bull Improved Using djangoconfurls (with djangoconfurlsdefaults as fallback)

bull Improved Adding CONTRIBUTINGrst

bull Improved Removed static Media inner class with fields

bull Improved Removed search icon with fields (has not being used)

bull Improved Added custom class attributes with filebrowser field

bull Improved Updated translations

bull Fixed fixed exception handling with python 25

bull Fixed fixes dir with SEARCH_TRAVERSE true and version select

bull Fixed Make Django FileUploadHandlers work (also fixed a memory leak)

bull Fixed return correct filename with OVERWRITE_EXISTING

bull Fixed fb_version_generate with FILEBROWSER_VERSIONS_BASEDIR

bull Fixed Table sorting with ascdesc

bull Fixed Added DeprecationWarning for FileObjectdirectory and FileObjectfolder

36 Chapter 6 Help

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

Django FileBrowser Documentation Release 357

514 Versions in Views

If you have a FileObject you can generateretrieve a version with

v = objimageversion_generate(version_prefix) returns a FileObject

515 Placeholder

When developing on a locale machine or a development-server you might not have all the images (resp media-files)available that are on your production instance and downloading these files on a regular basis might not be an option

In that case you can use a placeholder instead of a version You just need to define the PLACEHOLDER and overwritethe settings SHOW_PLACEHOLDER andor FORCE_PLACEHOLDER (see Placeholder)

516 Management Commands

fb_version_generateIf you need to generate certain (or all) versions type

python managepy fb_version_generate

fb_version_removeIf you need to generate certain (or all) versions type

python managepy fb_version_generate

Warning Please be very careful with this command

51 Versions 31

Django FileBrowser Documentation Release 357

32 Chapter 5 Image Versions

CHAPTER 6

Help

61 Help

611 FAQ

Why should I use the FileBrowser

If you need your editors or customers to manage files the FileBrowser is an alternative to an FTP-client Moreoveryou are able to define different image versions according to your websites grid Alternatives to the FileBrowser can befound at httpdjangopackagescomgridsgfile-managers

Do I need Grappelli

Grappelli is a requirement for using the FileBrowser There are several filebrowser-no-grappelli repositories (most ofthem on GitHub) but we donrsquot follow the development

I need help

see Troubleshooting

Why are there no fancy effects

The FileBrowser is about managing files We think that you should prepare your files before uploading them to theserver

How do I upload to another server

Use a custom storage engine see httpsdocsdjangoprojectcomen16howtocustom-file-storage

Why do I need image-versions

You need image-versions if your website is based on a grid

33

Django FileBrowser Documentation Release 357

Is the FileBrowser stable

Wersquove developed the FileBrowser for a couple of years and use it with almost all of our clients That said Grappelli isthe more stable and mature application

How can I contribute

Help is very much needed and appreciated Test the FileBrowser and submit feedbackpatches

Who develops the FileBrowser

The FileBrowser is developed and maintained by Patrick Kranzlmuumlller amp Axel Swoboda of vonautomatisch

612 Troubleshooting

Check your setup

Please check if the problem is caused by your setup

bull Read Quick start guide

bull Check if the staticmedia-files are served correctly

bull Make sure you have removed all custom FileBrowser templates from all locations in TEMPLATE_DIRS orcheck that these templates are compatible with the FileBrowser

Run the tests

Start the shell and type

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Check issues

If your setup is fine please check if your problem is a known issue

bull Take a look at all FileBrowser Issues (incuding closed) and search the FileBrowser Google-Group

Add a ticket

If you think yoursquove found a bug please add a ticket

bull Try to describe your problem as precisely as possible

bull Tell us what you did in order to solve the problem

bull Tell us what version of the FileBrowser you are using

bull Tell us what version of Django you are using

34 Chapter 6 Help

Django FileBrowser Documentation Release 357

bull Please do NOT add tickets if yoursquore having problems with serving staticmedia-files (because this is not relatedto the FileBrowser)

bull Please do NOT add tickets referring to Djangos trunk version

bull At best add a patch

Note Be aware that we may close issues not following these guidlines without further notifications

613 Translation

Translation is done via Transifex

Supported Languages

see httpswwwtransifexnetprojectspdjango-filebrowserresourcedjangopo

614 FileBrowser 35 Release Notes

FileBrowser 35 is compatible with Django 14151617 as well as Grappelli 242526

Update from FileBrowser 34x

bull Update Django to 14151617 and check httpsdocsdjangoprojectcomendevreleases14 orhttpsdocsdjangoprojectcomendevreleases15 or httpsdocsdjangoprojectcomendevreleases16

bull Update Grappelli to 24x25x26x

bull Update FileBrowser to 35x

62 Changelog

621 358 (not yet released)

622 357 (September 10th 2014)

bull New Compatibility with Django 17 and Grappelli 26x

bull Improved Updated tests because of the new random suffix with get_available_name (django storage)

bull Improved Added an icon in order to mark finished uploads

bull Improved Show resulting filename (eg with suffix converted) after successful upload

bull Fixed Permissions with file upload

bull Fixed Unified json response with _upload_file (no matter if file already exists or not)

623 356 (April 16th 2014)

bull Fixed Displaying pagination correctly with lots of entries

62 Changelog 35

Django FileBrowser Documentation Release 357

624 355 (April 13th 2014)

bull New Added client-side (JavaScript) file extension validation to the AJAX uploader

bull New Added experimental Python 33 support

bull Improved Tests with convertnormalize (removed special chars from test filename)

bull Fixed File selection after using search box (CKEditor)

bull Fixed Removed encoding of file URIs with CKEditor

625 354 (February 21st 2014)

bull Fixed Placeholder functionality (including tests)

bull Fixed Convertnormalize filenames (including tests)

bull Fixed Handling uppercase extensions with browse

626 353 (January 7 2014)

bull New added path_full to FileObject

bull Improved added docx to EXTENSIONS

bull Improved Recommend pillow instead of PIL as a requirement

bull Improved Added additional test cases

bull Improved Updated documentation

bull Improved Consistent use of storage (eg storagelocation storageurl)

bull Improved Removed unnecessary functions (eg url_join url_strip)

bull Improved Moved sort_by_attr to FileListing

bull Improved Regex matches with file versions on browse

bull Improved Using djangoconfurls (with djangoconfurlsdefaults as fallback)

bull Improved Adding CONTRIBUTINGrst

bull Improved Removed static Media inner class with fields

bull Improved Removed search icon with fields (has not being used)

bull Improved Added custom class attributes with filebrowser field

bull Improved Updated translations

bull Fixed fixed exception handling with python 25

bull Fixed fixes dir with SEARCH_TRAVERSE true and version select

bull Fixed Make Django FileUploadHandlers work (also fixed a memory leak)

bull Fixed return correct filename with OVERWRITE_EXISTING

bull Fixed fb_version_generate with FILEBROWSER_VERSIONS_BASEDIR

bull Fixed Table sorting with ascdesc

bull Fixed Added DeprecationWarning for FileObjectdirectory and FileObjectfolder

36 Chapter 6 Help

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

Django FileBrowser Documentation Release 357

32 Chapter 5 Image Versions

CHAPTER 6

Help

61 Help

611 FAQ

Why should I use the FileBrowser

If you need your editors or customers to manage files the FileBrowser is an alternative to an FTP-client Moreoveryou are able to define different image versions according to your websites grid Alternatives to the FileBrowser can befound at httpdjangopackagescomgridsgfile-managers

Do I need Grappelli

Grappelli is a requirement for using the FileBrowser There are several filebrowser-no-grappelli repositories (most ofthem on GitHub) but we donrsquot follow the development

I need help

see Troubleshooting

Why are there no fancy effects

The FileBrowser is about managing files We think that you should prepare your files before uploading them to theserver

How do I upload to another server

Use a custom storage engine see httpsdocsdjangoprojectcomen16howtocustom-file-storage

Why do I need image-versions

You need image-versions if your website is based on a grid

33

Django FileBrowser Documentation Release 357

Is the FileBrowser stable

Wersquove developed the FileBrowser for a couple of years and use it with almost all of our clients That said Grappelli isthe more stable and mature application

How can I contribute

Help is very much needed and appreciated Test the FileBrowser and submit feedbackpatches

Who develops the FileBrowser

The FileBrowser is developed and maintained by Patrick Kranzlmuumlller amp Axel Swoboda of vonautomatisch

612 Troubleshooting

Check your setup

Please check if the problem is caused by your setup

bull Read Quick start guide

bull Check if the staticmedia-files are served correctly

bull Make sure you have removed all custom FileBrowser templates from all locations in TEMPLATE_DIRS orcheck that these templates are compatible with the FileBrowser

Run the tests

Start the shell and type

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Check issues

If your setup is fine please check if your problem is a known issue

bull Take a look at all FileBrowser Issues (incuding closed) and search the FileBrowser Google-Group

Add a ticket

If you think yoursquove found a bug please add a ticket

bull Try to describe your problem as precisely as possible

bull Tell us what you did in order to solve the problem

bull Tell us what version of the FileBrowser you are using

bull Tell us what version of Django you are using

34 Chapter 6 Help

Django FileBrowser Documentation Release 357

bull Please do NOT add tickets if yoursquore having problems with serving staticmedia-files (because this is not relatedto the FileBrowser)

bull Please do NOT add tickets referring to Djangos trunk version

bull At best add a patch

Note Be aware that we may close issues not following these guidlines without further notifications

613 Translation

Translation is done via Transifex

Supported Languages

see httpswwwtransifexnetprojectspdjango-filebrowserresourcedjangopo

614 FileBrowser 35 Release Notes

FileBrowser 35 is compatible with Django 14151617 as well as Grappelli 242526

Update from FileBrowser 34x

bull Update Django to 14151617 and check httpsdocsdjangoprojectcomendevreleases14 orhttpsdocsdjangoprojectcomendevreleases15 or httpsdocsdjangoprojectcomendevreleases16

bull Update Grappelli to 24x25x26x

bull Update FileBrowser to 35x

62 Changelog

621 358 (not yet released)

622 357 (September 10th 2014)

bull New Compatibility with Django 17 and Grappelli 26x

bull Improved Updated tests because of the new random suffix with get_available_name (django storage)

bull Improved Added an icon in order to mark finished uploads

bull Improved Show resulting filename (eg with suffix converted) after successful upload

bull Fixed Permissions with file upload

bull Fixed Unified json response with _upload_file (no matter if file already exists or not)

623 356 (April 16th 2014)

bull Fixed Displaying pagination correctly with lots of entries

62 Changelog 35

Django FileBrowser Documentation Release 357

624 355 (April 13th 2014)

bull New Added client-side (JavaScript) file extension validation to the AJAX uploader

bull New Added experimental Python 33 support

bull Improved Tests with convertnormalize (removed special chars from test filename)

bull Fixed File selection after using search box (CKEditor)

bull Fixed Removed encoding of file URIs with CKEditor

625 354 (February 21st 2014)

bull Fixed Placeholder functionality (including tests)

bull Fixed Convertnormalize filenames (including tests)

bull Fixed Handling uppercase extensions with browse

626 353 (January 7 2014)

bull New added path_full to FileObject

bull Improved added docx to EXTENSIONS

bull Improved Recommend pillow instead of PIL as a requirement

bull Improved Added additional test cases

bull Improved Updated documentation

bull Improved Consistent use of storage (eg storagelocation storageurl)

bull Improved Removed unnecessary functions (eg url_join url_strip)

bull Improved Moved sort_by_attr to FileListing

bull Improved Regex matches with file versions on browse

bull Improved Using djangoconfurls (with djangoconfurlsdefaults as fallback)

bull Improved Adding CONTRIBUTINGrst

bull Improved Removed static Media inner class with fields

bull Improved Removed search icon with fields (has not being used)

bull Improved Added custom class attributes with filebrowser field

bull Improved Updated translations

bull Fixed fixed exception handling with python 25

bull Fixed fixes dir with SEARCH_TRAVERSE true and version select

bull Fixed Make Django FileUploadHandlers work (also fixed a memory leak)

bull Fixed return correct filename with OVERWRITE_EXISTING

bull Fixed fb_version_generate with FILEBROWSER_VERSIONS_BASEDIR

bull Fixed Table sorting with ascdesc

bull Fixed Added DeprecationWarning for FileObjectdirectory and FileObjectfolder

36 Chapter 6 Help

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

CHAPTER 6

Help

61 Help

611 FAQ

Why should I use the FileBrowser

If you need your editors or customers to manage files the FileBrowser is an alternative to an FTP-client Moreoveryou are able to define different image versions according to your websites grid Alternatives to the FileBrowser can befound at httpdjangopackagescomgridsgfile-managers

Do I need Grappelli

Grappelli is a requirement for using the FileBrowser There are several filebrowser-no-grappelli repositories (most ofthem on GitHub) but we donrsquot follow the development

I need help

see Troubleshooting

Why are there no fancy effects

The FileBrowser is about managing files We think that you should prepare your files before uploading them to theserver

How do I upload to another server

Use a custom storage engine see httpsdocsdjangoprojectcomen16howtocustom-file-storage

Why do I need image-versions

You need image-versions if your website is based on a grid

33

Django FileBrowser Documentation Release 357

Is the FileBrowser stable

Wersquove developed the FileBrowser for a couple of years and use it with almost all of our clients That said Grappelli isthe more stable and mature application

How can I contribute

Help is very much needed and appreciated Test the FileBrowser and submit feedbackpatches

Who develops the FileBrowser

The FileBrowser is developed and maintained by Patrick Kranzlmuumlller amp Axel Swoboda of vonautomatisch

612 Troubleshooting

Check your setup

Please check if the problem is caused by your setup

bull Read Quick start guide

bull Check if the staticmedia-files are served correctly

bull Make sure you have removed all custom FileBrowser templates from all locations in TEMPLATE_DIRS orcheck that these templates are compatible with the FileBrowser

Run the tests

Start the shell and type

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Check issues

If your setup is fine please check if your problem is a known issue

bull Take a look at all FileBrowser Issues (incuding closed) and search the FileBrowser Google-Group

Add a ticket

If you think yoursquove found a bug please add a ticket

bull Try to describe your problem as precisely as possible

bull Tell us what you did in order to solve the problem

bull Tell us what version of the FileBrowser you are using

bull Tell us what version of Django you are using

34 Chapter 6 Help

Django FileBrowser Documentation Release 357

bull Please do NOT add tickets if yoursquore having problems with serving staticmedia-files (because this is not relatedto the FileBrowser)

bull Please do NOT add tickets referring to Djangos trunk version

bull At best add a patch

Note Be aware that we may close issues not following these guidlines without further notifications

613 Translation

Translation is done via Transifex

Supported Languages

see httpswwwtransifexnetprojectspdjango-filebrowserresourcedjangopo

614 FileBrowser 35 Release Notes

FileBrowser 35 is compatible with Django 14151617 as well as Grappelli 242526

Update from FileBrowser 34x

bull Update Django to 14151617 and check httpsdocsdjangoprojectcomendevreleases14 orhttpsdocsdjangoprojectcomendevreleases15 or httpsdocsdjangoprojectcomendevreleases16

bull Update Grappelli to 24x25x26x

bull Update FileBrowser to 35x

62 Changelog

621 358 (not yet released)

622 357 (September 10th 2014)

bull New Compatibility with Django 17 and Grappelli 26x

bull Improved Updated tests because of the new random suffix with get_available_name (django storage)

bull Improved Added an icon in order to mark finished uploads

bull Improved Show resulting filename (eg with suffix converted) after successful upload

bull Fixed Permissions with file upload

bull Fixed Unified json response with _upload_file (no matter if file already exists or not)

623 356 (April 16th 2014)

bull Fixed Displaying pagination correctly with lots of entries

62 Changelog 35

Django FileBrowser Documentation Release 357

624 355 (April 13th 2014)

bull New Added client-side (JavaScript) file extension validation to the AJAX uploader

bull New Added experimental Python 33 support

bull Improved Tests with convertnormalize (removed special chars from test filename)

bull Fixed File selection after using search box (CKEditor)

bull Fixed Removed encoding of file URIs with CKEditor

625 354 (February 21st 2014)

bull Fixed Placeholder functionality (including tests)

bull Fixed Convertnormalize filenames (including tests)

bull Fixed Handling uppercase extensions with browse

626 353 (January 7 2014)

bull New added path_full to FileObject

bull Improved added docx to EXTENSIONS

bull Improved Recommend pillow instead of PIL as a requirement

bull Improved Added additional test cases

bull Improved Updated documentation

bull Improved Consistent use of storage (eg storagelocation storageurl)

bull Improved Removed unnecessary functions (eg url_join url_strip)

bull Improved Moved sort_by_attr to FileListing

bull Improved Regex matches with file versions on browse

bull Improved Using djangoconfurls (with djangoconfurlsdefaults as fallback)

bull Improved Adding CONTRIBUTINGrst

bull Improved Removed static Media inner class with fields

bull Improved Removed search icon with fields (has not being used)

bull Improved Added custom class attributes with filebrowser field

bull Improved Updated translations

bull Fixed fixed exception handling with python 25

bull Fixed fixes dir with SEARCH_TRAVERSE true and version select

bull Fixed Make Django FileUploadHandlers work (also fixed a memory leak)

bull Fixed return correct filename with OVERWRITE_EXISTING

bull Fixed fb_version_generate with FILEBROWSER_VERSIONS_BASEDIR

bull Fixed Table sorting with ascdesc

bull Fixed Added DeprecationWarning for FileObjectdirectory and FileObjectfolder

36 Chapter 6 Help

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

Django FileBrowser Documentation Release 357

Is the FileBrowser stable

Wersquove developed the FileBrowser for a couple of years and use it with almost all of our clients That said Grappelli isthe more stable and mature application

How can I contribute

Help is very much needed and appreciated Test the FileBrowser and submit feedbackpatches

Who develops the FileBrowser

The FileBrowser is developed and maintained by Patrick Kranzlmuumlller amp Axel Swoboda of vonautomatisch

612 Troubleshooting

Check your setup

Please check if the problem is caused by your setup

bull Read Quick start guide

bull Check if the staticmedia-files are served correctly

bull Make sure you have removed all custom FileBrowser templates from all locations in TEMPLATE_DIRS orcheck that these templates are compatible with the FileBrowser

Run the tests

Start the shell and type

python managepy test filebrowser

Warning Please note that the tests will copy files to your filesystem

Check issues

If your setup is fine please check if your problem is a known issue

bull Take a look at all FileBrowser Issues (incuding closed) and search the FileBrowser Google-Group

Add a ticket

If you think yoursquove found a bug please add a ticket

bull Try to describe your problem as precisely as possible

bull Tell us what you did in order to solve the problem

bull Tell us what version of the FileBrowser you are using

bull Tell us what version of Django you are using

34 Chapter 6 Help

Django FileBrowser Documentation Release 357

bull Please do NOT add tickets if yoursquore having problems with serving staticmedia-files (because this is not relatedto the FileBrowser)

bull Please do NOT add tickets referring to Djangos trunk version

bull At best add a patch

Note Be aware that we may close issues not following these guidlines without further notifications

613 Translation

Translation is done via Transifex

Supported Languages

see httpswwwtransifexnetprojectspdjango-filebrowserresourcedjangopo

614 FileBrowser 35 Release Notes

FileBrowser 35 is compatible with Django 14151617 as well as Grappelli 242526

Update from FileBrowser 34x

bull Update Django to 14151617 and check httpsdocsdjangoprojectcomendevreleases14 orhttpsdocsdjangoprojectcomendevreleases15 or httpsdocsdjangoprojectcomendevreleases16

bull Update Grappelli to 24x25x26x

bull Update FileBrowser to 35x

62 Changelog

621 358 (not yet released)

622 357 (September 10th 2014)

bull New Compatibility with Django 17 and Grappelli 26x

bull Improved Updated tests because of the new random suffix with get_available_name (django storage)

bull Improved Added an icon in order to mark finished uploads

bull Improved Show resulting filename (eg with suffix converted) after successful upload

bull Fixed Permissions with file upload

bull Fixed Unified json response with _upload_file (no matter if file already exists or not)

623 356 (April 16th 2014)

bull Fixed Displaying pagination correctly with lots of entries

62 Changelog 35

Django FileBrowser Documentation Release 357

624 355 (April 13th 2014)

bull New Added client-side (JavaScript) file extension validation to the AJAX uploader

bull New Added experimental Python 33 support

bull Improved Tests with convertnormalize (removed special chars from test filename)

bull Fixed File selection after using search box (CKEditor)

bull Fixed Removed encoding of file URIs with CKEditor

625 354 (February 21st 2014)

bull Fixed Placeholder functionality (including tests)

bull Fixed Convertnormalize filenames (including tests)

bull Fixed Handling uppercase extensions with browse

626 353 (January 7 2014)

bull New added path_full to FileObject

bull Improved added docx to EXTENSIONS

bull Improved Recommend pillow instead of PIL as a requirement

bull Improved Added additional test cases

bull Improved Updated documentation

bull Improved Consistent use of storage (eg storagelocation storageurl)

bull Improved Removed unnecessary functions (eg url_join url_strip)

bull Improved Moved sort_by_attr to FileListing

bull Improved Regex matches with file versions on browse

bull Improved Using djangoconfurls (with djangoconfurlsdefaults as fallback)

bull Improved Adding CONTRIBUTINGrst

bull Improved Removed static Media inner class with fields

bull Improved Removed search icon with fields (has not being used)

bull Improved Added custom class attributes with filebrowser field

bull Improved Updated translations

bull Fixed fixed exception handling with python 25

bull Fixed fixes dir with SEARCH_TRAVERSE true and version select

bull Fixed Make Django FileUploadHandlers work (also fixed a memory leak)

bull Fixed return correct filename with OVERWRITE_EXISTING

bull Fixed fb_version_generate with FILEBROWSER_VERSIONS_BASEDIR

bull Fixed Table sorting with ascdesc

bull Fixed Added DeprecationWarning for FileObjectdirectory and FileObjectfolder

36 Chapter 6 Help

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

Django FileBrowser Documentation Release 357

bull Please do NOT add tickets if yoursquore having problems with serving staticmedia-files (because this is not relatedto the FileBrowser)

bull Please do NOT add tickets referring to Djangos trunk version

bull At best add a patch

Note Be aware that we may close issues not following these guidlines without further notifications

613 Translation

Translation is done via Transifex

Supported Languages

see httpswwwtransifexnetprojectspdjango-filebrowserresourcedjangopo

614 FileBrowser 35 Release Notes

FileBrowser 35 is compatible with Django 14151617 as well as Grappelli 242526

Update from FileBrowser 34x

bull Update Django to 14151617 and check httpsdocsdjangoprojectcomendevreleases14 orhttpsdocsdjangoprojectcomendevreleases15 or httpsdocsdjangoprojectcomendevreleases16

bull Update Grappelli to 24x25x26x

bull Update FileBrowser to 35x

62 Changelog

621 358 (not yet released)

622 357 (September 10th 2014)

bull New Compatibility with Django 17 and Grappelli 26x

bull Improved Updated tests because of the new random suffix with get_available_name (django storage)

bull Improved Added an icon in order to mark finished uploads

bull Improved Show resulting filename (eg with suffix converted) after successful upload

bull Fixed Permissions with file upload

bull Fixed Unified json response with _upload_file (no matter if file already exists or not)

623 356 (April 16th 2014)

bull Fixed Displaying pagination correctly with lots of entries

62 Changelog 35

Django FileBrowser Documentation Release 357

624 355 (April 13th 2014)

bull New Added client-side (JavaScript) file extension validation to the AJAX uploader

bull New Added experimental Python 33 support

bull Improved Tests with convertnormalize (removed special chars from test filename)

bull Fixed File selection after using search box (CKEditor)

bull Fixed Removed encoding of file URIs with CKEditor

625 354 (February 21st 2014)

bull Fixed Placeholder functionality (including tests)

bull Fixed Convertnormalize filenames (including tests)

bull Fixed Handling uppercase extensions with browse

626 353 (January 7 2014)

bull New added path_full to FileObject

bull Improved added docx to EXTENSIONS

bull Improved Recommend pillow instead of PIL as a requirement

bull Improved Added additional test cases

bull Improved Updated documentation

bull Improved Consistent use of storage (eg storagelocation storageurl)

bull Improved Removed unnecessary functions (eg url_join url_strip)

bull Improved Moved sort_by_attr to FileListing

bull Improved Regex matches with file versions on browse

bull Improved Using djangoconfurls (with djangoconfurlsdefaults as fallback)

bull Improved Adding CONTRIBUTINGrst

bull Improved Removed static Media inner class with fields

bull Improved Removed search icon with fields (has not being used)

bull Improved Added custom class attributes with filebrowser field

bull Improved Updated translations

bull Fixed fixed exception handling with python 25

bull Fixed fixes dir with SEARCH_TRAVERSE true and version select

bull Fixed Make Django FileUploadHandlers work (also fixed a memory leak)

bull Fixed return correct filename with OVERWRITE_EXISTING

bull Fixed fb_version_generate with FILEBROWSER_VERSIONS_BASEDIR

bull Fixed Table sorting with ascdesc

bull Fixed Added DeprecationWarning for FileObjectdirectory and FileObjectfolder

36 Chapter 6 Help

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

Django FileBrowser Documentation Release 357

624 355 (April 13th 2014)

bull New Added client-side (JavaScript) file extension validation to the AJAX uploader

bull New Added experimental Python 33 support

bull Improved Tests with convertnormalize (removed special chars from test filename)

bull Fixed File selection after using search box (CKEditor)

bull Fixed Removed encoding of file URIs with CKEditor

625 354 (February 21st 2014)

bull Fixed Placeholder functionality (including tests)

bull Fixed Convertnormalize filenames (including tests)

bull Fixed Handling uppercase extensions with browse

626 353 (January 7 2014)

bull New added path_full to FileObject

bull Improved added docx to EXTENSIONS

bull Improved Recommend pillow instead of PIL as a requirement

bull Improved Added additional test cases

bull Improved Updated documentation

bull Improved Consistent use of storage (eg storagelocation storageurl)

bull Improved Removed unnecessary functions (eg url_join url_strip)

bull Improved Moved sort_by_attr to FileListing

bull Improved Regex matches with file versions on browse

bull Improved Using djangoconfurls (with djangoconfurlsdefaults as fallback)

bull Improved Adding CONTRIBUTINGrst

bull Improved Removed static Media inner class with fields

bull Improved Removed search icon with fields (has not being used)

bull Improved Added custom class attributes with filebrowser field

bull Improved Updated translations

bull Fixed fixed exception handling with python 25

bull Fixed fixes dir with SEARCH_TRAVERSE true and version select

bull Fixed Make Django FileUploadHandlers work (also fixed a memory leak)

bull Fixed return correct filename with OVERWRITE_EXISTING

bull Fixed fb_version_generate with FILEBROWSER_VERSIONS_BASEDIR

bull Fixed Table sorting with ascdesc

bull Fixed Added DeprecationWarning for FileObjectdirectory and FileObjectfolder

36 Chapter 6 Help

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

Django FileBrowser Documentation Release 357

627 352 (February 22 2013)

bull Fixed Use placeholder with version_generate (not only templatetags)

bull Fixed translate extension group name in upload form

bull Fixed updated filter dropdown HTML

bull Fixed Make setuppy work with Python 3

bull Fixed File submit with search traversal

bull Fixed Fixed fileobject path with Windows

bull Improved Throwing an exception when in DEBUG and version is not generated (with using the templatetag)

bull Compatibility with Django 15

628 351 (November 09 2012)

bull Fixed Documentation with Signals

bull Fixed File Upload using basic submission

bull Fixed Added site instance to Signals

bull Improved Donrsquot hide errors during generate-command

bull Improved Follow symlinks with generate-command

bull Improved Added some translations (eg for ldquoUpload Filerdquo)

bull New Setting OVERWRITE_EXISTING

bull New Added file signalspy

bull New Support for Django 15

629 350 (July 20 2012)

bull Compatibility with Django 14 and Grappelli 24

6210 343 (2062012)

bull Fixed a bug with versions not being generated (in case of capitalized extensions)

6211 342 (2632012)

bull Fixed security bug added staff_member_required decorator to the upload-function

bull Fixed a XSS vulnerability with fb_tags

62 Changelog 37

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

Django FileBrowser Documentation Release 357

6212 341 (732012)

bull Fixed an error with quotes (french translation) in uploadhtml

bull Updated translations

bull FileObject now returns path (with __unicode__ and __str__) instead of filename This is needed becauseotherwise formhas_changed will always be triggerde when using a FileBrowseField

bull Fixed a bug with versions and ldquof referenced before assignmentrdquo (eg when an image is being deleted)

bull Updated docs (warning that FILEBROWSER_MEDIA_ROOT and FILEBROWSER_MEDIA_URL will be re-moved with the next major release ndash use custom storage engine instead)

bull Fixed issue with MEDIA_URL hardcoded in tests

bull Fixed issue when MEDIA_URL starts with https

bull Fixed issue with default-site (if no site is given)

bull Fixed bug with using L10N and MAX_UPLOAD_SIZE in uploadhtml

bull Fixed small bug with importing Http404 in sitespy

bull Fixed bug with Fileobjectexists

bull Added NORMALIZE_FILENAME

6213 340 (15112011)

bull Final release of 34 see FileBrowser 35 Release Notes

38 Chapter 6 Help

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

CHAPTER 7

Main Features

bull Browse your media files with the admin interface

bull Multiple upload including a progress bar

bull Automatic thumbnails

bull Image versions to fit your websites grid (esp useful with adaptiveresponsive layouts)

bull Integration with TinyMCE

bull FileBrowseField to select imagesdocuments

bull FileInput and ClearableFileInput with image preview

bull Signals for upload rename and delete

bull Custom actions

bull Custom file storage engines

39

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

Django FileBrowser Documentation Release 357

40 Chapter 7 Main Features

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

CHAPTER 8

Code

httpsgithubcomsehmaschinedjango-filebrowser

41

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

Django FileBrowser Documentation Release 357

42 Chapter 8 Code

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

CHAPTER 9

Discussion

Use the FileBrowser Google Group to ask questions or discuss features

43

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

Django FileBrowser Documentation Release 357

44 Chapter 9 Discussion

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

CHAPTER 10

Versions and Compatibility

bull FileBrowser 358 (Development Version not yet released see Branch Stable35x)

bull FileBrowser 357 (September 10th 2014) Compatible with Django 14151617

Older versions are availabe at GitHub but are not supported anymore

45

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

Django FileBrowser Documentation Release 357

46 Chapter 10 Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

Index

Aadmin_versions() 17aspectratio 16

Ccommand line option

fb_version_generate 31fb_version_remove 31

Ddate 14datetime 15delete() 18delete_admin_versions() 18delete_versions() 18dimensions 15directory 16dirname 15

Eexists 15extension 14

Ffb_version_generate

command line option 31fb_version_remove

command line option 31FileBrowseField (built-in class) 19FileBrowserSite (built-in class) 23FileListing (built-in class) 11filename 14filename_lower 14filename_root 14FileObject (built-in class) 13files_listing_filtered() 12files_listing_total() 12files_walk_filtered() 12files_walk_total() 12filesize 14

filetype 14folder 16

Hhead 14height 16

Iis_empty 16is_folder 16is_version 16isdir() (built-in function) 25isfile() (built-in function) 25

Llisting() 11

Mmakedirs() (built-in function) 26mimetype 14move() (built-in function) 26

Oorientation 16original 17original_filename 17

Ppath 14 15path_full 15path_relative_directory 15

Rresults_listing_filtered() 13results_listing_total() 13results_walk_filtered() 13results_walk_total() 13

Uurl 15

47

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility

Django FileBrowser Documentation Release 357

Vversion_generate() 18version_name() 18version_path() 18versions() 17versions_basedir 17

Wwalk() 12width 16

48 Index

  • Installation and Setup
    • Quick start guide
    • Settings
      • API
        • API
          • Fields amp Widgets
            • Fields amp Widgets
              • Admin Interface
                • Admin Interface
                  • Image Versions
                    • Versions
                      • Help
                        • Help
                        • Changelog
                          • Main Features
                          • Code
                          • Discussion
                          • Versions and Compatibility