title: Unit testing django project with sqlite3 db missing tables
body: <p><a href="https://stackoverflow.com/questions/7336130/missing-table-when-running-django-unittest-with-sqlite3">Missing Table When Running Django Unittest with Sqlite3</a></p>
  
  <p>I have already looked at this post and am trying to set up my project for testing.  Anytime I try to run any of the database commands I get an error.  The problem that I'm running into is when I attempt to do a manage.py syncdb I get a Database Error saying that no such table exists even though it is currently in a models file as well as the production database.</p>
  
  <p>Here is the traceback.</p>
  
  <pre><code>brandon@Brandon-PC:~/course-management$ ./manage.py test Testing.SimpleTest
  Traceback (most recent call last):
    File "./manage.py", line 11, in &lt;module&gt;
      execute_manager(settings)
    File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/core/management/__init__.py", line 438, in execute_manager
      utility.execute()
    File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/core/management/__init__.py", line 379, in execute
      self.fetch_command(subcommand).run_from_argv(self.argv)
    File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/core/management/base.py", line 191, in run_from_argv
      self.execute(*args, **options.__dict__)
    File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/core/management/base.py", line 220, in execute
      output = self.handle(*args, **options)
    File "/usr/local/lib/python2.7/dist-packages/South-0.7.3-py2.7.egg/south/management/commands/test.py", line 8, in handle
      super(Command, self).handle(*args, **kwargs)
    File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/core/management/commands/test.py", line 37, in handle
      failures = test_runner.run_tests(test_labels)
    File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/test/simple.py", line 358, in run_tests
      suite = self.build_suite(test_labels, extra_tests)
    File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/test/simple.py", line 245, in build_suite
      suite.addTest(build_test(label))
    File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/test/simple.py", line 107, in build_test
      app_module = get_app(parts[0])
    File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/db/models/loading.py", line 129, in get_app
      self._populate()
    File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/db/models/loading.py", line 61, in _populate
      self.load_app(app_name, True)
    File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/db/models/loading.py", line 78, in load_app
      models = import_module('.models', app_name)
    File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/utils/importlib.py", line 35, in import_module
      __import__(name)
    File "/home/brandon/course-management/Course/models.py", line 223, in &lt;module&gt;
      class CourseDelivery(models.Model):
    File "/home/brandon/course-management/Course/models.py", line 262, in CourseDelivery
      Language = models.ForeignKey('Utilities.Language', default=Language.objects.get(Code='en'))
    File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/db/models/manager.py", line 132, in get
      return self.get_query_set().get(*args, **kwargs)
    File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/db/models/query.py", line 344, in get
      num = len(clone)
    File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/db/models/query.py", line 82, in __len__
      self._result_cache = list(self.iterator())
    File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/db/models/query.py", line 273, in iterator
      for row in compiler.results_iter():
    File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/db/models/sql/compiler.py", line 680, in results_iter
      for rows in self.execute_sql(MULTI):
    File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/db/models/sql/compiler.py", line 735, in execute_sql
      cursor.execute(sql, params)
    File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/db/backends/sqlite3/base.py", line 234, in execute
      return Database.Cursor.execute(self, query, params)
  django.db.utils.DatabaseError: no such table: Utilities_language
  </code></pre>
  
  <p>this is in my settings.py file</p>
  
  <pre><code>if 'test' in sys.argv or 'jenkins' in sys.argv:
  DATABASES = {
               'default': {
                           'ENGINE': 'django.db.backends.sqlite3',
                           'NAME': 'test_ndptc'
                           }
               }
  </code></pre>
  
  <p>The same error also occurs if I set the above if statement to true and attempt to run manage.py syncdb.</p>
  
  <p>Here is the model that's causing the issue.  </p>
  
  <pre><code>class CourseDelivery(models.Model):
  """
  """
  Course = models.ForeignKey(Course)
  TrainingMethod = models.ForeignKey(TrainingMethod)
  DeliveryType = models.ForeignKey(DeliveryType)
  Location = models.ForeignKey(Address, null=True)
  Lat = models.FloatField()
  Lon = models.FloatField()
  StartDate = models.DateTimeField()
  EndDate = models.DateTimeField()
  FinishDate = models.DateField(null=True)
  ConfirmationCode = models.CharField(max_length=8, editable=False, unique=True)
  Reported = models.BooleanField()
  ReportedDate = models.DateField(null=True)
  SequenceNumber = models.IntegerField(null=True)
  Status = models.IntegerField()
  HostingAgency = models.TextField(null=True, blank=True)
  MaximumEnrollment = models.IntegerField(null=True, blank=True)
  ContactInformation = models.TextField(null=True, blank=True)
  ArrivalTime = models.TextField(null=True, blank=True)
  CourseMaterials = models.TextField(null=True, blank=True)
  Internet = models.TextField(null=True, blank=True)
  Food = models.TextField(null=True, blank=True)
  Parking = models.TextField(null=True, blank=True)
  Requirements = models.TextField(null=True, blank=True)
  AdditionalInformation = models.TextField(null=True, blank=True)
  ReadingMaterials = models.TextField(null=True, blank=True)
  SpecialNote = models.TextField(null=True, blank=True)
  CertificateEmailsSent = models.BooleanField(default=False)
  RegistrationCloseDate = models.DateTimeField(null=True, blank=True)
  ReminderDate = models.DateTimeField(null=True, blank=True)
  PreTestCloseDate = models.DateTimeField(null=True, blank=True)
  PostTestCloseDate = models.DateTimeField(null=True, blank=True)
  EvaluationCloseDate = models.DateTimeField(null=True, blank=True)
  ParticipantGuide = models.ForeignKey('Course.Document', null=True, blank=True)
  Flyer = models.FileField(upload_to='flyers/%Y/%m', null=True, blank=True)
  UpdateUser = models.ForeignKey(User, null=True)
  UpdateDate = models.DateField(null=True)
  Language = models.ForeignKey('Utilities.Language', default=Language.objects.get(Code='en'))
  
  def save(self):
      # If this is the first time around, or AUTO_COMPUTE_DATES is true, compute the dates.
      if self.Status &amp; CourseDeliveryStatus.AUTO_COMPUTE_DATES:
          self.RegistrationCloseDate   = self.StartDate - datetime.timedelta(days=REGISTRATION_CLOSE_DATE)
          self.ReminderDate            = self.StartDate - datetime.timedelta(days=REMINDER_DATE)
          self.PreTestCloseDate        = self.StartDate - datetime.timedelta(days=PRE_TEST_CLOSE_DATE)
          self.PostTestCloseDate       = self.EndDate   + datetime.timedelta(days=POST_TEST_CLOSE_DATE)
          self.EvaluationCloseDate     = self.EndDate   + datetime.timedelta(days=EVALUATION_CLOSE_DATE)
          self.FinishDate              = self.EndDate   + datetime.timedelta(days=FINISH_DATE)
      elif self.id == None:
          if not self.RegistrationCloseDate:
              self.RegistrationCloseDate   = self.StartDate - datetime.timedelta(days=REGISTRATION_CLOSE_DATE)
          if not self.ReminderDate:
              self.ReminderDate            = self.StartDate - datetime.timedelta(days=REMINDER_DATE)
          if not self.PreTestCloseDate:
              self.PreTestCloseDate        = self.StartDate - datetime.timedelta(days=PRE_TEST_CLOSE_DATE)
          if not self.PostTestCloseDate:
              self.PostTestCloseDate       = self.EndDate   + datetime.timedelta(days=POST_TEST_CLOSE_DATE)
          if not self.EvaluationCloseDate:
              self.EvaluationCloseDate     = self.EndDate   + datetime.timedelta(days=EVALUATION_CLOSE_DATE)
          if not self.FinishDate:
              self.FinishDate              = self.EndDate   + datetime.timedelta(days=FINISH_DATE)
  
      # If the course does not have a code, create one.
      if not self.ConfirmationCode:
          self.ConfirmationCode = ''.join(Random().sample(string.digits, 5))
      #Course.functions.geocode_course_delivery(self)
      super(CourseDelivery, self).save()
  
  def __unicode__(self):
      return unicode(self.StartDate.strftime('%m/%d/%Y')) + ' - ' + self.Course.CourseName \
          + ' (' + unicode(self.Location.City) + ', ' + unicode(self.Location.State) + ')'
  
  def registration_date_passed(self):
      today = datetime.date.today()
      if today &gt; self.RegistrationCloseDate.date():
          return True
      return False
  
  def registration_open(self):
      # Do not allow registrations after the course has been reported.
      if self.Reported:
          return False
  
      # Check that the closing dates and enrollment are good.
      today = datetime.date.today()
      if self.Status &amp; CourseDeliveryStatus.ONLINE_REGISTRATION:
          if self.RegistrationCloseDate.date() &lt; today:
              return False
  
          # Make sure that the MaximumEnrollment is greater than the participant count
          if not self.wait_list_enabled() and self.MaximumEnrollment:
              participant_count = Participant.objects.filter(CourseDelivery=self).count()
              if not self.MaximumEnrollment - participant_count &gt; 0:
                  return False
          return True
      return False
  
  def wait_list_enabled(self):
      if self.Status &amp; CourseDeliveryStatus.WAIT_LIST:
          return True
      return False
  
  def get_form(self, form_type):
      package = CourseDeliveryForms.objects.filter(CourseDelivery=self.id).get(FormType=form_type).FormPackage
      __import__(package.FormModule)
      return eval(package.FormName)
  
  def get_model(self, form_type):
      package = CourseDeliveryForms.objects.filter(CourseDelivery=self.id).get(FormType=form_type).FormPackage
      __import__(package.ModelModule)
      return eval(package.ModelName)
  
  def get_template(self, form_type):
      package = CourseDeliveryForms.objects.filter(CourseDelivery=self.id).get(FormType=form_type).FormPackage
      return package.Template
  
  def default_language(self):
      return Language.objects.get(Code='en')
  </code></pre>