0

I am using python 3.3 and django 1.6 and working with django-filebrowser.

I would like to automatically create the any missing folders based on the description in the model class. For example if the model says this:

class Marketing(models.Model):
    marketing_title = models.CharField(max_length=20)
    marketing_image = FileBrowseField("Image", max_length=200, directory="/frontpage/marketing", blank=True, null=True)

    def __str__(self):

I would then like for a folder structure named frontpage/marketing to be created within the media/uploads folder. Then when my users to go admin and add an image, the search icon should automatically open up to the correct directory for upload.

Currently, when I click the search icon it just goes to the base directory media/uploads

user1026169
  • 4,067
  • 5
  • 17
  • 25
  • i don't know what else to try besides the `directory` setting within the `marketing_image` object. what you see is what i've tried. – user1026169 Mar 16 '14 at 00:28
  • Well, if you needed to do something in Python when a module loaded, where would that go? – Brandon Mar 16 '14 at 00:42
  • i can tell your trying to help me think this through...but i'm not following how to unravel that inner bits of django-filebrowser in this case... – user1026169 Mar 16 '14 at 00:51
  • Actually, you don't really need to be concerned with filebrowser at all. You just need to create a directory if one doesn't exist, correct? You can do this with pure Python code in the `__init__.py` of your app module. Check out: http://stackoverflow.com/questions/273192/check-if-a-directory-exists-and-create-it-if-necessary. Any code in your `__init__.py` will be executed when then module is loaded, so that's a great place to put the code. – Brandon Mar 16 '14 at 00:52
  • wow. ok, so thats not a typical 'django' answer, although it does make sense. so your saying i should forget trying to do this using django-filebrowser and instead and write extra code to do it manually? i like the idea in principle, however i also want django-filebrowser to open the correct folder from admin. – user1026169 Mar 16 '14 at 01:02
  • You can still set the folder like you want in your FileBrowseField, so it will go to that directory when you click the search icon, but your `__init__` code can create the directory ahead of time if it doesn't already exist. – Brandon Mar 16 '14 at 01:35

1 Answers1

0

I had this problem for a project using Grappelli, TinyMCE V3 and FileBrowser:

https://groups.google.com/d/msg/django-grappelli/kvZG9nD9OpM/bsuROsYjEQAJ

I solved it by adding code to the model's SAVE function to create the desired folder when the user SAVES the record.

import os
from django.conf import settings

class Job(models.Model):
    def save(self, *args, **kwargs):
        job_path = os.path.join(settings.MEDIA_ROOT, settings.FILEBROWSER_DIRECTORY, self.number)
        try:
            logger.debug("Trying to create folder %s", job_path)
            os.makedirs(job_path)
            logger.debug('---    Job Folder created!       ---')
        except OSError:
            if not os.path.isdir(job_path):
                logger.debug('---    Job Folder creation error!  ---')
                raise
            else:
                logger.debug('---    Job Folder already exists!  ---')
        # Call 'real' save method:
        super(Job, self).save(*args, **kwargs) # Call the "real" save() method.

This builds the target folder name with absolute path on the server. Then it creates the folder if its not there already. There is a lot of "discussion" whether its Cricket to use OSError to detect if the folder already exists. If your on the "other" side of the debate, feel free to use an IF statement with isdir() first instead.

The next part is a change to the start of the custom filebrowse function:

function CustomFileBrowser(field_name, url, type, win) {
  var cmsURL = '/admin/filebrowser/browse/?pop=2';
  var mypath = mypath = django.jQuery('#id_number').attr('value');
  console.log("mypath using #id: " + mypath);
  if (!mypath) {
    mypath = django.jQuery('div.grp-readonly')[0].innerHTML;
    console.log("mypath readonly: " + mypath);
  }
  cmsURL = cmsURL + '&type=' + type;
  cmsURL = cmsURL + '&dir=' + mypath;
  console.log(cmsURL);

  tinyMCE.activeEditor.windowManager.open({ })
    ... rest of function ...
}

Because my form has a read-only mode for low level users, the field that holds the folder name may be displayed as an "input" field, or as read-only DIV text. The first attempt to define mypath works for input fields. The IF detects if that failed (mypath will be NULL) and tries grabbing it from the HTML text. I'm not happy with my DIV selector, if the order of fields changes it will likely start grabbing the wrong one. But it will do for now. After (hopefully) finding the right folder name, I then append it to the FileBrowser URL as '&dir=folder'. This is making use of the fact FileBrowser looks for a "dir" value in the calling URL. If found, it tries to CD to it before it opens the browser. Very handy. Not sure its documented, I found it whilst reading the source code for FileBrowser....

If FileBrowser can't CD into the folder, it will display a pretty pink error message. I have trained staff to "fix" that by backing out of the file browser and image inserter dialogs, press SAVE AND CONTINUE - which creates the folder - and try again.

Hope this helps somebody else!

Rich.

Richard Cooke
  • 613
  • 6
  • 14