yeomandev
yeomandev

Reputation: 11806

Why is the django admin area throwing an error when I try to access my app?

I have started a blog application. The model looks like this:

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=512)
    image = models.ImageField(upload_to='/pathto/blogImages')
    body = models.TextField()
    visible = models.BooleanField()
    date_created = models.DateTimeField(auto_now_add=True)
    date_updated = models.DateTimeField(auto_now=True)

    def __unicode__(self):
        return self.title

class Tag(models.Model):
    keyword = models.CharField(max_length=256)
    posts = models.ManyToManyField(Post)

    def __unicode__(self):
        return self.keyword

After running syncdb, I then created an admin.py file that looks like this:

from blog.models import Post
from blog.models import Tag
from django.contrib import admin

class TagInline(admin.TabularInline):
    model = Tag
    extra = 3

class PostAdmin(admin.ModelAdmin):
    inlines = [TagInline]

admin.site.register(Post, PostAdmin)

When I access the admin area (http://localhost:8000/admin/blog/post/add/) I get the following error:

Exception at /admin/blog/post/add/
<class 'blog.models.Tag'> has no ForeignKey to <class 'blog.models.Post'>
Request Method: GET
Request URL:    http://localhost:8000/admin/blog/post/add/
Django Version: 1.4.1
Exception Type: Exception
Exception Value:    
<class 'blog.models.Tag'> has no ForeignKey to <class 'blog.models.Post'>
Exception Location: /usr/local/lib/python2.7/dist-packages/django/forms/models.py in _get_foreign_key, line 800
Python Executable:  /usr/bin/python
Python Version: 2.7.3

When I looked up many-to-may relationships in django I found https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/. I haven't been able to find what I'm missing. How do I avoid the error?

Upvotes: 0

Views: 215

Answers (3)

eusid
eusid

Reputation: 769

your many to many field should be on the post model not the tag model. objects must be defined in order or you must models.ManyToManyField('tag') this is not recommended unless unavoidable. so define tag first then post so you can do with just (tag) under post model. i would suggest just using django tagging. it has always served me well.

after all thats what makes django so appealing is reusable apps and fast development.

Upvotes: 0

arie
arie

Reputation: 18982

As you are dealing with a many to many relation your InlineModelAdmin should look like this:

class TagInline(admin.TabularInline):
    model = Tag.posts.through

Upvotes: 1

Torsten Engelbrecht
Torsten Engelbrecht

Reputation: 13496

Maybe you can try setting the model field for posts to

posts = models.ManyToManyField(Post, null=True, blank=True).

I guess the post might not be created, so it is not able to create a tag or "connect" a tag with a post.

Upvotes: 0

Related Questions