Jayanth
Jayanth

Reputation: 587

How to work with Django ManyToManyField and django admin

I seem to be having a problem with ManyToMany relationships in Django, I do not seem to be getting the right admin screen on this. I wanted to display a stackedinline for the address field, however I'm getting only a dropbox. Could somebody help, below is my code.

Models.py

class AddressType(models.Model):
    TypeCode = models.CharField('Address Type', max_length=50, blank=False, null = False)
    Description = models.TextField('Description')
    def __unicode__(self):
        return self.TypeCode

class Address(models.Model):
    AddressType = models.ForeignKey(AddressType)
    Address = models.TextField('Address', blank=False, null=False)

    def __unicode__(self):
        return self.AddressType.TypeCode


class BusinessPartner(models.Model):
    FullName = models.CharField('Full Name', max_length=50, blank=False, null=False)
    PartnerType = models.ForeignKey(PartnerType)
    Company = models.CharField('Company', max_length=100, blank=True, null=True)
    Website = models.URLField('Website', blank=True, null=True)
    Address = models.ManyToManyField(Address,through='AddressPartner_Assn')

    def __unicode__(self):
        if self.Company:
            return self.FullName + '-' + self.Company
        else:
            return self.FullName

class AddressPartner_Assn(models.Model):
    Address = models.ForeignKey(Address)
    BusinessPartner = models.ForeignKey(BusinessPartner)

Admins.py
=========
class AddressTypeAdmin(admin.ModelAdmin):
    list_display = ('TypeCode','Description')
    search_fields = ['TypeCode','Description']

class AddressAdmin(admin.ModelAdmin):
    list_display = ['Address']
    search_fields = ['Address']
    list_filter = ['AddressType']

class AddressInlineAdmin(admin.StackedInline):
    model = BusinessPartner.Address.through
    extra = 1

class BusinessPartnerAdmin(admin.ModelAdmin):
    list_display = ('__unicode__','FullName','PartnerType','Company')
    inlines = [AddressInlineAdmin,]
    search_fields = ['FullName','Company']
    list_filter = ('PartnerType',)
    raw_id_fields = ('PartnerType',)

Upvotes: 0

Views: 244

Answers (1)

Rohan
Rohan

Reputation: 1041

Since you are using through argument to mentioned the intermediate table explicitly you'll have to replace AddressInlineAdmin with

class AddressInlineAdmin(admin.StackedInline):
    model = AddressPartner_Assn
    extra = 1

Please refer to https://docs.djangoproject.com/en/1.4/ref/contrib/admin/#working-with-many-to-many-intermediary-models for any additional information

Upvotes: 1

Related Questions