Baron Young
Baron Young

Reputation: 311

How can I display the contents of a related table within the Django admin change form?

I'm new to programming, Python, and Django, so your patience is appreciated. I have been writing a practice application in Django for storing cooking recipes. I have two models:

class Recipe(models.Model):
    recipe_name = models.CharField(max_length=30)
    recipe_instructions = models.TextField()
    recipe_whyitworks = models.TextField(verbose_name="Why It Works")
    recipe_date = models.DateField()
    def __str__(self):
       return self.recipe_name
    def was_published_recently(self):
       return self.recipe_date >= timezone.now() -datetime.timedelta(days=5)

class Ingredient(models.Model):
    recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)
    ingredient_name = models.CharField(max_length=30)
    ingredient_qty = models.DecimalField(verbose_name='Quantity', max_digits=3, decimal_places=2)
    ingredient_uom = models.CharField(verbose_name='Unit of Measure', max_length=15)
    def __str__(self):
        return self.ingredient_name

I have admin set to be able to edit either table:

from django.contrib import admin

# Register your models here.
from .models import Recipe, Ingredient

admin.site.register(Recipe)
admin.site.register(Ingredient)

What I want to do is when I click on an "Ingredient" I would like it to show all previous ingredients added to the recipe, along with the quantity and unit of measure for each in a table, in addition to the fields which allow me to add a new one. Thanks in advance for your help!

Upvotes: 1

Views: 514

Answers (1)

Ashish Acharya
Ashish Acharya

Reputation: 3399

You can add inlines like this:

admin.py

from django.contrib import admin

class IngredientInline(admin.TabularInline):
    model = Ingredient

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

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

Upvotes: 2

Related Questions