Django 1.2.1许多字段的内联管理员

时间:2010-06-30 20:13:27

标签: django django-admin django-forms

我最近升级到了Django 1.2.1,因为我对have basic many-to-many inline fields的能力特别感兴趣。当像这样使用管理员时:

初始模型:

class Ingredient(models.Model):
    name = models.TextField()

class Recipe(models.Model):
    ingredients = models.ManyToManyField(Ingredient)

初始管理员:

class IngredientInline(admin.TabularInline):
      model = Recipe.ingredients.through

class RecipeOptions(admin.ModelAdmin):
    inlines = [IngredientInline,]
    exclude = ('ingredients',)

admin.site.register(Recipe,RecipeOptions)        

我得到的是与您在ManyToMany字段中通常看到的相同的形式,还有一些额外的行。为它提供额外的参数,如Ingredient ModelForm没有帮助。通过model = Foo.manyfields.through怀疑基本的ModelForm关联可能有问题,我决定看看中间模型是否有帮助。它现在通过以下方式显示工作内联表单:

新模特:

class RecipeJoin(models.Model):
    pass

class Recipe(models.Model):
    ingredients = models.ManyToManyField(RecipeJoin,through='Ingredient')

class Ingredient(models.Model):  
    name = models.TextField()
    test = models.ForeignKey(RecipeJoin,null=True,blank=True,editable=False)

新管理员:

class IngredientInline(admin.TabularInline):
    model = Recipe.ingredients.through

class RecipeOptions(admin.ModelAdmin):
    inlines = [IngredientInline,]

admin.site.register(Recipe,RecipeOptions)

显然这不是我想要使用的黑客攻击。任何人都知道如何通过内联形式显示多种关系,而无需(a)创建全新的BasicInline表单和模板,或者(b)通过中间(或通用管理员)模型进行显示?

TIA。 (我为冗长而道歉,这是我的第一篇文章,所以想要彻底)。

2 个答案:

答案 0 :(得分:24)

这些例子中的一个是否完成了你想要做的事情?

一个:

# Models:

class Ingredient(models.Model):
    name = models.CharField(max_length=128)

class Recipe(models.Model):
    name = models.CharField(max_length=128)
    ingredients = models.ManyToManyField(Ingredient, through='RecipeIngredient')

class RecipeIngredient(models.Model):
    recipe = models.ForeignKey(Recipe)
    ingredient = models.ForeignKey(Ingredient)
    amount = models.CharField(max_length=128)


# Admin:

class RecipeIngredientInline(admin.TabularInline):
    model = Recipe.ingredients.through

class RecipeAdmin(admin.ModelAdmin):
    inlines = [RecipeIngredientInline,]

class IngredientAdmin(admin.ModelAdmin):
    pass

admin.site.register(Recipe,RecipeAdmin)
admin.site.register(Ingredient, IngredientAdmin)

B:

# Models:

class Recipe(models.Model):
    name = models.CharField(max_length=128)

class Ingredient(models.Model):
    name = models.CharField(max_length=128)
    recipe = models.ForeignKey(Recipe)


# Admin:

class IngredientInline(admin.TabularInline):
    model = Ingredient

class RecipeAdmin(admin.ModelAdmin):
    inlines = [IngredientInline,]

admin.site.register(Recipe,RecipeAdmin)

答案 1 :(得分:0)

如果我没记错的话(自从我完成这部分以来已经有一段时间了),你需要为Ingredient添加admin并将其设置为具有自定义ModelForm。然后该表格将用于成分的内联版本。