Django Admin return lines with more than one model

Let's say I have some django models, something like this:

class Address(models.Model): pass class Person(models.Model): address = models.ForeignKey(Address) class Store(models.Model): address = models.ForeignKey(Address) class Company(models.Model): address = models.ForeignKey(Address) 

So, in the Admin interface, I would like to be able to edit Person and have the address in the line.

I know it's possible

 class Address(models.Model): person = models.ForeignKey(Person, blank=True) store = models.ForeignKey(Store, blank=True) company = models.ForeignKey(Company, blank=True) class Person(models.Model): pass class Store(models.Model): pass class Company(models.Model): pass 

Then I can do the usual

 class AddressInline(admin.TabularInline): model = Address class PersonAdmin(admin.ModelAdmin): model = Person inlines = (AddressInLine,) class CompanyAdmin(admin.ModelAdmin): and so on 

But that means that I would have more than one address per person, and my address model would no longer feel.

Any help would be appreciated.

+8
python django
source share
2 answers

Try to execute

 from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic class Address(models.Model): object_id = models.PositiveIntegerField() content_type = models.ForeignKey(ContentType) of = generic.GenericForeignKey('content_type', 'object_id' ) class Person(models.Model): pass class Store(models.Model): pass class Company(models.Model): pass 

Then you can do this:

 from django.contrib import admin from django.contrib.contenttypes import generic class AddressInline(generic.GenericStackedInline): model = Address max_num = 1 class PersonAdmin(admin.ModelAdmin): model = Person inlines = (AddressInLine,) class CompanyAdmin(admin.ModelAdmin): and so on admin.site.register(Person, PersonAdmin) 
+4
source share

Changing the AddressInline (admin.TabularInline) class to the AddressInline (admin.StackedInline) class will make the inline address look smaller than it is possible to have several.

Set AddressInline.max_num to 1 if you want no more than 1 address in the address bar.

Set AddressInline.extra to 1 if you want an empty address form when there is no corresponding address.

Documentation: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#inlinemodeladmin-options

+2
source share

All Articles