Global name not defined error in Django/Python trying to set foreignkey

Posted by Mark on Stack Overflow See other posts from Stack Overflow or by Mark
Published on 2010-05-31T23:54:03Z Indexed on 2010/06/01 0:03 UTC
Read the original article Hit count: 181

Filed under:
|
|
|
|

Summary:
I define a method createPage within a file called PageTree.py that takes a Source model object and a string.
The method tries to generate a Page model object.
It tries to set the Page model object's foreignkey to refer to the Source model object which was passed in.
This throws a NameError exception!

I'm trying to represent a website which is structured like a tree. I define the Django models Page and Source, Page representing a node on the tree and Source representing the contents of the page. (You can probably skip over these, this is a basic tree implementation using doubly linked nodes).

class Page(models.Model):
    name = models.CharField(max_length=50)
    parent = models.ForeignKey("self", related_name="children", null=True);
    firstChild = models.ForeignKey("self", related_name="origin", null=True);
    nextSibling = models.ForeignKey("self", related_name="prevSibling", null=True);
    previousSibling = models.ForeignKey("self", related_name="nxtSibling", null=True);
    source = models.ForeignKey("Source");


class Source(models.Model):    
    #A source that is non dynamic will be refered to as a static source
    #Dynamic sources contain locations that are names of functions
    #Static sources contain locations that are places on disk
    name = models.CharField(primary_key=True, max_length=50)
    isDynamic = models.BooleanField()
    location = models.CharField(max_length=100);

I've coded a python program called PageTree.py which allows me to request nodes from the database and manipulate the structure of the tree. Here is the trouble making method:

def createPage(pageSource, pageName):
    page = Page()
    page.source = pageSource
    page.name = pageName
    page.save()
    return page

I'm running this program in a shell through manage.py in Windows 7

manage.py shell
from mysite.PageManager.models import Page, Source
from mysite.PageManager.PageTree import *
... create someSource = Source(), populate the fields, and save it ...
createPage(someSource, "test")
...
NameError: global name 'source' is not defined

When I type in the function definition for createPage into the shell by hand, the call works without error. This is driving me bonkers and help is appreciated.

© Stack Overflow or respective owner

Related posts about python

Related posts about django