如何将grand foreignkey字段添加到管理表单

时间:2014-07-18 19:37:51

标签: python django django-models django-admin

我有以下models.py

from django.db import models
import datetime

from taggit.managers import TaggableManager

class Category(models.Model):
    title = models.CharField(max_length=200, help_text='Maximum 250 characters')
    slug = models.SlugField(unique=True)

    def __unicode__(self):
        return self.title

    class Meta:
        ordering = ['title']
        verbose_name_plural = "Categories"


class Notebook(models.Model):
    category = models.ForeignKey(Category)
    title = models.CharField(max_length=200, help_text='Maximum 250 characters')
    slug = models.SlugField(unique=True)
    last_modified = models.DateTimeField()



    def __unicode__(self):
        return self.title


class Page(models.Model):
    notebook = models.ForeignKey(Notebook)
    title = models.CharField(max_length=200)
    slug = models.SlugField(unique_for_date='pub_date')
    content = models.TextField()
    tags = TaggableManager()
    pub_date = models.DateTimeField(default=datetime.datetime.now)

    def __unicode__(slef):
        return self.title

    def save(self, *args, **kwargs):
        super(Page, self).save(*args, **kswargs)
        self.notebook.save()

现在,当我在admin.py中注册Page模型时。我得到一个表单,我可以从下拉列表中选择notebook。但notebook本身有一个foreignKey类别。我现在有两个问题。

  1. 当我尝试添加新页面时,如何获取顶部有两个下拉列表的表单,一个用于Category,另一个用于Notebook

  2. 当我尝试添加新的Category时,如何获取可以同时添加新Notebook和新Page的表单?

  3. 我可以通过

    Page添加新的add Category
    class PageInline(admin.StackedInline):
        model = Page
        extra = 1
    
    class NotebookAdmin(admin.ModelAdmin):
        inlines = [PageInline]
    

    当我尝试对此进行同样的操作时,CategoryAdmin我收到错误消息,指出Page没有foreignKey Category

0 个答案:

没有答案