River Tam
River Tam

Reputation: 3216

NameError: name 'Tag' is not defined

I'm creating the model for my django site (python, if that's not obvious).

from django.db import models

class Picture(models.Model):
        name = models.CharField(max_length=100)
        pub_date = models.DateTimeField('date published')
        tags = models.ManyToManyField(Tag)
        owner = models.ForeignKey(User)

class Tag(models.Model):
        pics = models.ManyToManyField(Picture)
        name = models.CharField(max_length=30)

class User(models.Model):
        name = models.CharField(max_length=20)
        date_joined = models.DateTimeField('date joined')

class Comment(models.Model):
        content = models.CharField(max_length=500)
        date = models.DateTimeField('date commented')
        commenter = models.ForeignKey(User)
        pic = models.ForeignKey(Picture)

That's the entire current model, but I'm getting an error on the line tags = models.ManyToManyField(Tag), saying "NameError: name 'Tag' is not defined"

What's the deal with that?

Upvotes: 0

Views: 5537

Answers (1)

machineghost
machineghost

Reputation: 35730

You declare Tag after you declare Picture, but Picture uses Tag, so it's not defined at the time you try to use it. Just change the order of your classes and it should solve things.

In other words, change your code to:

class Tag(models.Model):
    pics = models.ManyToManyField(Picture)
    name = models.CharField(max_length=30)

# Hurray, Tag exists now

class Picture(models.Model):
    name = models.CharField(max_length=100)
    pub_date = models.DateTimeField('date published')

    # Therefore, this next line will work

    tags = models.ManyToManyField(Tag)
    owner = models.ForeignKey(User)

(minus my comments)

Upvotes: 1

Related Questions