Django filebrowser,FileBrowserField的模型特定目录参数 [英] Django filebrowser, model specific directory parameter for FileBrowserField

查看:444
本文介绍了Django filebrowser,FileBrowserField的模型特定目录参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用django-filebrowser和 FileBrowserField 我正在尝试根据一个键分配目录模型本身。所以使用博客示例,如果我正在保存不同帖子的照片,这些照片将在以博客ID命名的目录中。因此,如果 MEDIA_ROOT / some / path / to / media / filebrowser_files / 我希望动态分配目录 paramter为 MEDIA_ROOT + str(model_pk)

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)

这一点我试图做类似于以下的事情,但不明白如何获取当前对象的id。 (DoesNotExist异常与没有异常提供)我知道尝试使用self.page存在错误,但我不知道如何正确地做到这一点。有人可以提供一些洞察力,我的逻辑在哪里有缺陷,我能做些什么来解决它?非常感谢。

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


推荐答案

我意识到我没有看到更近你的代码self.page将不起作用,因为您正在初始化Model实例,并且self.page尚未设置为数据库中的页面。您应该尝试:

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)

做你想要的只有在你在PageImage中分配了一个页面到该字段。

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

这篇关于Django filebrowser,FileBrowserField的模型特定目录参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆