1

Using django-filebrowser and the FileBrowserField I am attempting to assign the directory parameter based off a key in the model itself. So using a blog example, if I were saving photos for different posts, the photos would be in directories named after the blog id. So if the MEDIA_ROOT was/some/path/to/media/filebrowser_files/ I wish to dynamically assign the directory paramter to be MEDIA_ROOT+str(model_pk)

At this point I have attempted to do something resembling the following, but do not understand how to obtain the id of the current object. (DoesNotExist exception with "No exception supplied") I know the error exists within the attempt to use self.page, but I do not know how to do this correctly. Could someone provide some insight as to where my logic is flawed and what I can do to fix it? Thanks much.

class PageImage(models.Model):
    page = models.ForeignKey(Page)
    page_photo = FileBrowseField("Image", max_length=200, blank=True, null=True)
    def __init__(self, *args, **kwargs):
        super(PageImage, self).__init__(*args, **kwargs)
        path = settings.MEDIA_ROOT+'pages/unfiled/'
        if self.page:
            path = settings.MEDIA_ROOT+'pages/'+str(self.page)+'/'
        if not os.path.exists(path):
            os.makedirs(path)
        self._meta.get_field_by_name("page_photo")[0].directory = path
wilbbe01
  • 1,931
  • 1
  • 24
  • 38

1 Answers1

1

I realize I didn't look closer at your code. self.page will not work because you're initializing the Model instance and self.page has not been set to a page in the database. You should try instead:

class PageImage(models.Model):
    page = models.ForeignKey(Page)
    page_photo = FileBrowseField("Image", max_length=200, blank=True, null=True)

    def save(self, *args, **kwargs):

        path = settings.MEDIA_ROOT+'pages/unfiled/'
        if self.page:
            path = settings.MEDIA_ROOT+'pages/'+str(self.page)+'/'
        if not os.path.exists(path):
            os.makedirs(path)
        self._meta.get_field_by_name("page_photo")[0].directory = path
        super(PageImage, self).save(*args, **kwargs)

doing what you want only after you've assigned a Page to the field in PageImage.

Kenny Shen
  • 4,773
  • 3
  • 21
  • 18
  • Thanks for the answer. The Page model has nothing unusual. The problem is with the usage of self I believe as I can remove everything but the call to super init and a print(str(self.page)). That is where I get a DoesNotExist exception stating No exception supplied. No overriding of pk by me. – wilbbe01 Oct 27 '11 at 05:07
  • Thanks for the updated answer. That at least gets me doing what I was trying to, but I think I need to rethink how I'm doing it. Setting `directory` doesn't do much on the save since the image is already uploaded...so I'll need to maybe move images from wherever they were uploaded on save instead. File management...fun. Thanks again. – wilbbe01 Oct 28 '11 at 00:55