Django filebrowser, model specific directory parameter for FileBrowserField

◇◆丶佛笑我妖孽 提交于 2019-12-11 05:08:43

问题


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.



来源:https://stackoverflow.com/questions/7911172/django-filebrowser-model-specific-directory-parameter-for-filebrowserfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!