开发者

Showing file size in django admin

开发者 https://www.devze.com 2023-03-13 05:51 出处:网络
I have a django app with some model for uploading files. I need to show different fields when creating new object and showing existing one.

I have a django app with some model for uploading files. I need to show different fields when creating new object and showing existing one. I have the following admin class:

class ResourceAdminForCustomer(ModelAdmin):

    list_display = ["name", "type", "size"]
    list_filter = ['type']

    def get_form(self, request, obj=None, **kwargs):
        if obj:
            self.fields = ("name", "type", "size", "tags")
        else:
            self.fields = ("name", "type", "media", "description", "tags")
        return super(ResourceAdminForCustomer, self).get_form(request, obj, \
                                                              **kwargs)

    def size(self, obj):
        file = '%s/customers/%s/resources/%s' \
             % (settings.MEDIA_ROOT, obj.customer, obj.media.name.split("/")[-1])
        if os.path.exists(file):
            return "%0.1f KB" % (os.path.getsize(file)/(1024.0))
开发者_运维百科        return "0 MB"

When I try to open the form I get:

Caught AttributeError while rendering: 'NoneType' object has no attribute 'label'

So how can I insert the value of size function as a read_only field to my self.fields?

Thanks.


Set 'readonly_fields' in ModelAdmin to make result of 'size' readonly in both list and edit views.

You can also override get_readonly_fields ModelAdmin method if you wish to set readonly fields depending of request and current object.

Readonly fields have been added to ModelAdmin in Django 1.2:

https://docs.djangoproject.com/en/1.3/ref/contrib/admin/#django.contrib.admin.ModelAdmin.fields

0

精彩评论

暂无评论...
验证码 换一张
取 消