Search code examples
djangosubform

Does Django Admin Site have Subform?


Say there're two tables:

table: Company field: ID, Company_Name

table: People field: ID, People_Name, Company_ID

I used to use MS Access, create a people form, a company form, then bind people form into company form as a "Subform".

Now I am learning Django. Are there any ways to achieve the similar function.

Thanks in advance.


Solution

  • If you mean to edit both Company and People from the same screen, yes, these are called "Inline forms" in Django.

    For using them in the admin site, see:
    https://docs.djangoproject.com/en/dev/ref/contrib/admin/#inlinemodeladmin-objects

    For the more general case (in your own views), see:
    https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#inline-formsets

    eg (in yourapp/admin.py)

    from django.contrib import admin
    from .models import Company, People
    
    class PeopleInline(admin.TabularInline):
        model = People
    
    class CompanyAdmin(admin.ModelAdmin):
        inlines = [
            PeopleInline,
        ]