简体   繁体   中英

model inheritance + django admin

I am reusing the News model from cmsplugin_news, just adding some extra fields in my inheriting model. (Multi-table inheritance, just as explained here .

from cmsplugin_news.models import News

class News(News):
    departments = models.ManyToManyField('department.Department', blank=True, related_name="news")

On my admin.py I am extending NewsAdmin to set my own form:

class MyNewsAdmin(NewsAdmin):
    form = NewsModelForm

Which I have defined in forms.py:

from news.models import News

class NewsModelForm(NewsForm):
    class Meta:
        model = News
        widgets = {
            'excerpt': CKEditorWidget(config_name='basic'),
            'content': CKEditorWidget(config_name='default')
        }

    def _get_widget(self):
        from ckeditor.widgets import CKEditorWidget
        return CKEditorWidget()

The model inheritance seems to work well when I save objects from the shell console. But when I try to create a MyNews object from the django admin and link it to a department, this field is not saved. Or at least this change is not shown anywhere

unicms-testnews=> select * from cmsplugin_news_news;
 id | title | slug | excerpt | content | is_published |        pub_date        |            created            |            updated            | link 
----+-------+------+---------+---------+--------------+------------------------+-------------------------------+-------------------------------+------
  1 | dfad  | dfad |         |         | f            | 2013-09-10 13:44:46+02 | 2013-09-10 13:45:04.709556+02 | 2013-09-10 13:57:05.568696+02 | 
(1 row)
unicms-testnews=> select * from news_news;
 news_ptr_id 
-------------
           1
(1 row)

unicms-testnews=> select * from news_news_departments;
 id | news_id | department_id 
----+---------+---------------
  1 |       1 |             1
(1 row)

I can't understand anything, can anyone help me please? Thank you very much!

You created a form for News , that also exist in your DB since the model is not abstract, not for MyNews . Thus your current form has no field for the departments attribute, even if you add a widget with an input for it. Do the code bellow instead:

class MyNewsForm(NewsForm):
    class Meta:
        model = MyNews # instead of just News
        ...

What Django does in background is to create two relations: the cmsplugin_news_news stores all the News fields, and the news_news_departments stores your new field and is in one-to-one relation with the first relation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM