简体   繁体   中英

django admin. Create parent with child in same form

I have two classes in my model.py

class User(models.Model):
  name = models.CharField()
  phone = models.CharField()
  # Other common fields

class Customer(User):
  payment = models.CharField()
  user__id = models.OneToOneField('User', db_column='id', primary_key=True)

class Company(User):
  address = models.CharField()
  user_id = models.OneToOneField('User', db_column='id', primary_key=True)

When I use the admin of Customer/Company it includes all User fields, that is perfect for me. But this form of Customer/Company also includes a dropdown list with the foreign key of an User, and I don't want to create the User first and then the Customer/Company object. I want that when I fill the Customer/Company form (with User fields) I should create the User object too.

Is there a way to solve this without create a User instance prior the Customer/Company instance?

Thanks

You can do this by adding an inline in your model registration in admin.py .

class AInline(admin.TabularInline):
    model = A

class BAdmin(admin.ModelAdmin):
    inlines = [AInline]

admin.register(A)
admin.register(B, BAdmin)

Django inline model admin documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM