django-nonrel exclude listfield from admin

六月ゝ 毕业季﹏ 提交于 2019-12-13 04:23:12

问题


I've ran into a typical problem where I have a ListField in a model.

I'd like to use the Django admin to play around with the object and the ListField isn't that crucial, it's a list of embedded objects that I can live without.

When I use this, I get the error on the main admin page. If I don't use the ModelAdmin object when registering the original Item object, I only get the error if I try to add an Item.

from django.contrib import admin

class ItemAdmin(admin.ModelAdmin):
    exclude = ('bids',)

admin.site.register(Item, ItemAdmin)

How to properly exclude the "bids" ListField then?


回答1:


I worked round it by making my ListField non editable, as I couldnt get exclude to work for me either..

eg:

class Item(models.Model):
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)
    title = models.CharField(max_length=255)
    bids = ListField(EmbeddedModelField('Bid'), editable=False)



回答2:


Subclass ListField and override formfield so that it returns None.

Returning None from formfield(...) means that the field should be excluded from all forms, so you need remove the exclude = ['bids'] thing from your ModelAdmin.

Alternatively, you can make formfield(...) return a proper forms.Field subclass -- to display e.g. a text version, use something like

class Item(models.Model):
    def formfield(self, **kwargs):
        return super(Item, self).formfield(form_class=YourCustomFormField, **kwargs)

To exclude it from the admin, you can still use exclude.

https://docs.djangoproject.com/en/dev/howto/custom-model-fields/#django.db.models.Field.formfield

Put your field subclass into yourapp/fields.py.



来源:https://stackoverflow.com/questions/8866880/django-nonrel-exclude-listfield-from-admin

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