Django filebrowser, model specific directory param

2019-07-28 18:35发布

问题:

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

回答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.