Django 1.2.1 Inline Admin for Many To Many Fields

后端 未结 2 904
花落未央
花落未央 2021-02-07 18:04

I recently upgraded to Django 1.2.1 because I was specifically interested in the ability to have basic many-to-many inline fields. When using the admin like so:

Initial

相关标签:
2条回答
  • 2021-02-07 18:42

    Do one of these examples accomplish what you are trying to do?

    a:

    # 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)
    
    0 讨论(0)
  • 2021-02-07 18:54

    If I remember correctly (and it's been a while since I've done this part), you need to add the admin for Ingredient and set it to have the custom ModelForm. Then that form will be used in the inline version of Ingredient.

    0 讨论(0)
提交回复
热议问题