Question

I have these classes in the models.py of my django application.I am using postgresql 8.3 as database

class Course(models.Model):
    students = models.ManyToManyField(User)
    title = models.CharField(max_length=200)
    description = models.TextField()

    def __unicode__(self):
        return self.title

    class Meta:
        verbose_name_plural="Courses"

class CourseChoicesForm(forms.Form):
    courseoption = forms.ChoiceField(choices=[(x.id,x.title) for x in Course.objects.all()])

When I run python manage.py syncdb ,I get an error which says the relation course is not found

...
File "/home/me/Django-1.4/django/utils/importlib.py", line 35, in import_module
    __import__(name)
  File "/home/me/dev/python/django/myprj/myapp/models.py", line 50, in <module>
    class CourseChoicesForm(forms.Form):
  File "/home/me/dev/python/django/myprj/myapp/models.py", line 52, in CourseChoicesForm
    courseoption = forms.ChoiceField(choices=[(x.id,x.title) for x in Course.objects.all()])
...
File "/home/me/Django-1.4/django/db/backends/postgresql_psycopg2/base.py", line 52, in execute
    return self.cursor.execute(query, args)
django.db.utils.DatabaseError: relation "myapp_course" does not exist

UPDATE: I solved this as follows

class CourseChoicesForm(forms.Form):
    courseoption = forms.ChoiceField(choices=[],required=False)
    def __init__(self, *args, **kwargs):
        super(CourseChoicesForm, self).__init__(*args, **kwargs)
        self.fields['courseoption'].choices = [(x.id,x.title) for x in Course.objects.all()]

Still,I am not quite sure why this behaviour occurred.Can someone please explain?

Was it helpful?

Solution

It's not good practise to put your forms inside your models.py file, and this is exactly why.

For syncdb to run, it first needs to load your models files. This certainly has to happen before it can make any database updates.

Now, your models.py file also includes a form class, and that class definition relies on the table being present. (That's just part of the way that Python works -- your class definitions are executed at the time the module is imported). So, before the table could be added, syncdb had to load a module which required that the table be present.

When you changed your form class, you moved the line that depended on the new table -- now it's inside an __init__ method. Unlike the class definition, that method does not get run at import time. It only runs when you actually create a form object. Now syncdb can import your new module and update the database, and everything works as it should.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top