Tutorial :admin template for manytomany


I have a manytomany relationship between publication and pathology. Each publication can have many pathologies. When a publication appears in the admin template, I need to be able to see the many pathologies associated with that publication. Here is the model statement:

class Pathology(models.Model):      pathology = models.CharField(max_length=100)      def __unicode__(self):          return self.pathology      class Meta:          ordering = ["pathology"]    class Publication(models.Model):      pubtitle = models.TextField()      pathology = models.ManyToManyField(Pathology)      def __unicode__(self):          return self.pubtitle      class Meta:          ordering = ["pubtitle"]  

Here is the admin.py. I have tried variations of the following, but always get an error saying either publication or pathology doesn't have a foreign key associated.

from myprograms.cpssite.models import Pathology  class PathologyAdmin(admin.ModelAdmin):      # ...      list_display = ('pathology', 'id')    admin.site.register(Pathology, PathologyAdmin)    class PathologyInline(admin.TabularInline):      #...      model = Pathology      extra = 3    class PublicationAdmin(admin.ModelAdmin):      # ...      ordering = ('pubtitle', 'year')      inlines = [PathologyInline]  admin.site.register(Publication,PublicationAdmin)  

Thanks for any help.


Unless you are using a intermediate table as documented here http://docs.djangoproject.com/en/dev/ref/contrib/admin/#working-with-many-to-many-intermediary-models, I don't think you need to create an Inline class. Try removing the line includes=[PathologyInline] and see what happens.


I realize now that Django is great for the administration (data entry) of a website, simple searching and template inheritance, but Django and Python are not very good for complex web applications, where data is moved back and forth between a database and an html template. I have decided to combine Django and PHP, hopefully, applying the strengths of both. Thanks for you help!


That looks more like a one-to-many relationship to me, tho I'm somewhat unclear on what exactly Pathologies are. Also, so far as I understand, Inlines don't work on manytomany. That should work if you flip the order of the models, remove the manytomany and add a ForeignKey field to Publication in Pathology.

class Publication(models.Model):      pubtitle = models.TextField()      def __unicode__(self):          return self.pubtitle      class Meta:          ordering = ["pubtitle"]    class Pathology(models.Model):      pathology = models.CharField(max_length=100)      publication = models.ForeignKey(Publication)      def __unicode__(self):          return self.pathology      class Meta:          ordering = ["pathology"]  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »