Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django no ForeignKey...But it's a ManyToManyField

My admin is working fine other than one big roadbump. I've created a manytomany relationship between posts and tags. I can CRUD tags in my admin but for some reason, I get the following error message:

Exception at /admin/website/post/add/

<class 'website.models.Tag'> has no ForeignKey to <class 'website.models.Post'

Here are my models:

class Post(models.Model):

  user=models.ForeignKey(User, unique=True)
  title=models.CharField(max_length=80)
  slug=models.SlugField()
  description=models.TextField(max_length=1000, blank=True)
  created=models.DateField(auto_now_add=True)
  #following info is for processing purposes
  management_phone=models.CharField(max_length=200, blank=True)
  management_email=models.CharField(max_length=200, blank=True)
  processing=models.BooleanField(default=False)
  transacted=models.BooleanField(default=False)
  manually_closed=models.BooleanField(default=False)

  def __unicode__(self):
      return self.title 

class Tag(models.Model):
   title=models.CharField(max_length=100)
   posts=models.ManyToManyField(Post, blank=True,null=True)

   def __unicode__(self):
        Return self.title

Again, the problem only emerges when I try to Add a Post instance

I have a database table "website_tag_posts" in my database for the relationship. What's the problem here?

Thanks

like image 210
Ben Avatar asked Dec 17 '22 16:12

Ben


1 Answers

Sounds to me like you set up your Post ModelAdmin with a Tag Inline.

ManyToMany is not a foreign key, so you can't set up an Inline like that.

If you want an inline, specify the through model for your m2m field as the model instead. The through table for the m2m field contains the ForeignKey to your Post table.

table tag <- table tag_post -> table post

class TagInline(admin.StackedInline):
     model = Tag.posts.through
like image 121
Yuji 'Tomita' Tomita Avatar answered Jan 03 '23 16:01

Yuji 'Tomita' Tomita