0

environment using: ubuntu 18, python 2.7, django version 1.8.2

I am migrating the work environment from one PC to another by cloning git repo. But on new PC I am getting error: django.db.utils.OperationalError: no such table: tableName for all commands like python manage.py runserver/makemigrations/migrate/flush etc

I spend whole day looking for solution. Link with same problem:

django.db.utils.OperationalError: no such table: price_category AFTER GIT CLONE

Make migrations error in django: "no such table"

and many more

The common solution given in all these answer:

  1. delete all migration file except init.py (ques: should i also keep init.pyc?)
  2. delete database
  3. run makemigrations/migrate

I had done 1st. For 2nd google says to delete .sqlite3 file but I wasnt able to find it In settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'IITMSAT_Telecommands_database',
    }
}

Structure of Folders (I deleted things marked with red lines)

Error:

  File "manage.py", line 24, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 312, in execute
    django.setup()
  File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 108, in populate
    app_config.import_models(all_models)
  File "/usr/local/lib/python2.7/dist-packages/django/apps/config.py", line 198, in import_models
    self.models_module = import_module(models_module_name)
  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/home/spacelab/groundstationsoftware/MCS/Telemetry/models.py", line 304, in <module>
    class Short_Beacon(models.Model):
  File "/home/spacelab/groundstationsoftware/MCS/Telemetry/models.py", line 308, in Short_Beacon
    session                     = models.IntegerField(default=get_current_sub_pass())
  File "/home/spacelab/groundstationsoftware/MCS/Telecommands/models.py", line 32, in get_current_sub_pass
    print(Satellite_Pass.objects.filter(passing_now=1))
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 138, in __repr__
    data = list(self[:REPR_OUTPUT_SIZE + 1])
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 162, in __iter__
    self._fetch_all()
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 965, in _fetch_all
    self._result_cache = list(self.iterator())
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 238, in iterator
    results = compiler.execute_sql()
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 840, in execute_sql
    cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 79, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 97, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/sqlite3/base.py", line 318, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: Telecommands_satellite_pass

models.py of telecommands folder

from traceback import print_tb
from django.db import models
from django.db.models import signals
from django.dispatch import Signal
from django.core.validators import MinValueValidator, MaxValueValidator
from datetime import datetime,timedelta
from django.contrib.auth.models import User, AbstractBaseUser
from django.utils import timezone

from Telecommands.signals import mail
from django.db.models.signals import pre_save

class CustomUser(models.Model):
    user = models.OneToOneField(User)
    phone_number = models.BigIntegerField()


class Pending(User):
    class Meta:
        proxy = True
        app_label = 'auth'
        verbose_name_plural = 'Users - Pending'
signals.pre_save.connect(mail, sender=User)


def get_current_pass():
    return Satellite_Pass.objects.filter(passing_now=1).order_by('-passing_slot')[0]


def get_current_sub_pass():
    print(99999999999999999999999999999)
    print(Satellite_Pass.objects.filter(passing_now=1))
    return Satellite_Pass.objects.filter(passing_now=1).order_by('-passing_slot')[0].sat_session_value


class Satellite_Pass(models.Model):
    """
    Model to store data for all unique passes
    """
    sat_session_value = models.PositiveSmallIntegerField(default=1,validators=[MinValueValidator(1)])
    # Unique value for each pass
    passing_slot = models.IntegerField( primary_key=True )
    passing_now = models.PositiveSmallIntegerField(default=0,validators=[MinValueValidator(0),MaxValueValidator(1)])
    passing_date = models.DateField()
    # Telecommands_timeout = models.DateTimeField(default=datetime.now)
    # Model to save different time
    rise_time = models.TimeField()
    set_time = models.TimeField()
    pass_duration = models.CharField(max_length=20)
    # def get_pass_time(self):
    # return (self.set_time - self.rise_time)
    # pass_duration = models.TimeField(default=get_pass_time)

    closest_time = models.TimeField()
    # Azimuthal angle
    rise_azimuth = models.DecimalField(max_digits=10, decimal_places=6)
    set_azimuth = models.DecimalField(max_digits=10, decimal_places=6)
    # Max Elevation of satellite
    max_elevation = models.DecimalField(max_digits=10, decimal_places=6)
    def __unicode__(self):
        return str(self.passing_slot)


class TC_Template(models.Model):
    """
    Models to store all data for templates
    """
    template_name       = models.CharField(max_length = 50)
    template_number     = models.AutoField(primary_key=True)
    to_display          = models.BooleanField(default=True)

    template_freq       = models.IntegerField(default=0)
    created_by          = models.ForeignKey(User,related_name='created_by')
    modified_by         = models.ForeignKey(User,related_name='modified_by')
    modification_time   = models.DateTimeField(default=timezone.now)
    
    def __unicode__(self):
        return str(self.template_name)


class TC_Packet_Base(models.Model):
    """
    Abstract class for Telecommands.
    attributes:
        packet_id       : primary_key
        template_number : TC_List id from TC_Template model
        rest - TC Protocol parameters
    """
    # TODO: figure out max length possible for app_data3 - update comments
    # TODO: app_data is possibly unused. Remove app_data if not used.

    packet_id = models.AutoField(primary_key=True)
    template_number = models.IntegerField()
    service_choices = (
        ('TVS','TVS'),
        ('MMS','MMS'),
        ('PMS','PMS'),
        ('FMS','FMS'),
        ('OBOSC','OBOSC'),
        ('LDTS','LDTS'),
        ('OBSRS','OBSRS'),
    )
    service = models.CharField(max_length=5,choices = service_choices)
    sub_service = models.PositiveSmallIntegerField(validators=[MinValueValidator(0),MaxValueValidator(15)])
    apid_choices = (
        ('COM','COM'),
        ('BAE','BAE'),
        ('CDMS','CDMS'),
        ('SPEED','SPEED'),
    )
    apid = models.CharField(max_length=7,choices=apid_choices)

    app_data1 = models.CharField(max_length=50, blank=True)
    app_data2 = models.CharField(max_length=50, blank=True)
    app_data3 = models.CharField(max_length=50, blank=True)
    app_data  = models.CharField(blank=True, max_length=260)
    app_data_string = models.TextField(blank=True)

    long_short = models.PositiveSmallIntegerField(validators=[MaxValueValidator(1),MinValueValidator(0)])

    ack = models.BooleanField(default=False)
    abort_on_NACK = models.BooleanField()

    comments = models.TextField(blank=True)

    class Meta:
        abstract = True
    def __unicode__(self):
        return str(self.service)


# This contains all packets for the template
class TC_Packet(TC_Packet_Base):
    """
    This contains all packets for the template
    """
    packet_order = models.IntegerField(validators=[MinValueValidator(0)])
    # class Mete:
    #   ordering = ['-template_number','packet_order']


# This model contaions all telecommands which are sent to satellite
class TC_Sent_Packet(TC_Packet_Base):
    """
    This model contains all telecommands which are sent to satellite

    """
    packet_order = models.IntegerField(validators=[MinValueValidator(0)])
    packet_seq_count = models.IntegerField(validators=[MinValueValidator(0)])
    next_psc = models.IntegerField(validators=[MinValueValidator(1)])
    # Status of the telecommands as of now
    is_enabled = models.BooleanField(default=True)
    is_retry_allowed = models.BooleanField(default=True)
    is_resend_allowed = models.BooleanField(default=True)

    # Pass and session
    passing_slot = models.ForeignKey(Satellite_Pass,related_name='pass_slot_sent',default=get_current_pass)
    sub_pass = models.PositiveSmallIntegerField(validators=[MinValueValidator(1)],default=get_current_sub_pass)

    # unique value to all packets in one pass
    send_by = models.ForeignKey(User,related_name='send_by')

    # Senders name will be saved here
    send_datetime = models.DateTimeField(default=timezone.now)

    # time of sending this packet will be saved
    resend_tries = models.IntegerField(default=0,validators=[MaxValueValidator(20),MinValueValidator(-1)])
    resend_times = models.IntegerField(default=0,validators=[MaxValueValidator(20),MinValueValidator(-1)])
    remarks = models.CharField(blank=True,max_length=100)
    # Number of resend_tries to send the telecommands to satellite if NACK is received

    # ack_L1_status = models.NullBooleanField()
    ack_L1 = models.IntegerField(default=-1,validators=[MinValueValidator(-1),MaxValueValidator(4)])
    ack_L2 = models.NullBooleanField()
    ack_L3 = models.NullBooleanField()
    ack_L4 = models.NullBooleanField()
    error_code = models.CharField(max_length=10,blank=True)
    error_status = models.CharField(max_length=300,blank=True,default="Not yet received")
    nack = models.NullBooleanField()


class Long_Beacon(models.Model):
    recieved_on = models.DateTimeField(default=timezone.now)
    passing_slot = models.ForeignKey(Satellite_Pass,related_name='pass_slot_long_beacon',default=get_current_pass)
    call_sign = models.CharField(max_length=100)

    polarization_choices = (
        ('LHCP','LHCP'),
        ('RHCP','RHCP'),
    )
    polarization = models.CharField(max_length=10,choices=polarization_choices)

    raw_data = models.TextField(blank=True)


class Sent_TC_QM_Validation(models.Model):
    TC_ID              = models.IntegerField(null=True)
    TC_List_Name       = models.CharField(blank=True, max_length=50)
    Telecommand_Name   = models.CharField(blank=True, max_length=50)
    Table_Name         = models.CharField(blank=True, max_length=50)
    Parameter          = models.CharField(blank=True, max_length=50)
    Expected_Value_Min = models.CommaSeparatedIntegerField(null=True, max_length=50)
    Expected_Value_Max = models.CommaSeparatedIntegerField(null=True, max_length=50)
    Time_Stamp         = models.DateTimeField(timezone.now)
    Received_Value     = models.CommaSeparatedIntegerField(null=True, max_length=50)
    Success            = models.NullBooleanField()
    Comments           = models.CharField(blank=True, max_length=50)

    def parameters(self):
        from re import split
        return split(r',', str(self.Parameter))

    def expected_val(self):
        from re import split
        return split(r',', str(self.Expected_Value_Min)), split(r',', str(self.Expected_Value_Max))

migration folder in telecommands:

0001_initial.py

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
import datetime
from django.conf import settings
import django.core.validators
import Telecommands.models


class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='CustomUser',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('phone_number', models.BigIntegerField()),
                ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.CreateModel(
            name='Long_Beacon',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('recieved_on', models.DateTimeField(default=datetime.datetime.now)),
                ('call_sign', models.CharField(max_length=100)),
                ('polarization', models.CharField(max_length=10, choices=[(b'LHCP', b'LHCP'), (b'RHCP', b'RHCP')])),
                ('raw_data', models.TextField(blank=True)),
            ],
        ),
        migrations.CreateModel(
            name='Satellite_Pass',
            fields=[
                ('sat_session_value', models.PositiveSmallIntegerField(default=1, validators=[django.core.validators.MinValueValidator(1)])),
                ('passing_slot', models.IntegerField(serialize=False, primary_key=True)),
                ('passing_now', models.PositiveSmallIntegerField(default=0, validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(1)])),
                ('passing_date', models.DateField()),
                ('rise_time', models.TimeField()),
                ('set_time', models.TimeField()),
                ('pass_duration', models.CharField(max_length=20)),
                ('closest_time', models.TimeField()),
                ('rise_azimuth', models.DecimalField(max_digits=10, decimal_places=6)),
                ('set_azimuth', models.DecimalField(max_digits=10, decimal_places=6)),
                ('max_elevation', models.DecimalField(max_digits=10, decimal_places=6)),
            ],
        ),
        migrations.CreateModel(
            name='TC_Packet',
            fields=[
                ('packet_id', models.AutoField(serialize=False, primary_key=True)),
                ('template_number', models.IntegerField()),
                ('service', models.CharField(max_length=5, choices=[(b'TVS', b'TVS'), (b'MMS', b'MMS'), (b'PMS', b'PMS'), (b'FMS', b'FMS'), (b'OBOSC', b'OBOSC'), (b'LDTS', b'LDTS'), (b'OBSRS', b'OBSRS')])),
                ('sub_service', models.PositiveSmallIntegerField(validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(15)])),
                ('apid', models.CharField(max_length=7, choices=[(b'COM', b'COM'), (b'BAE', b'BAE'), (b'CDMS', b'CDMS'), (b'SPEED', b'SPEED')])),
                ('app_data1', models.CharField(max_length=50, blank=True)),
                ('app_data2', models.CharField(max_length=50, blank=True)),
                ('app_data3', models.CharField(max_length=50, blank=True)),
                ('app_data', models.CharField(max_length=260, blank=True)),
                ('app_data_string', models.TextField(blank=True)),
                ('long_short', models.PositiveSmallIntegerField(validators=[django.core.validators.MaxValueValidator(1), django.core.validators.MinValueValidator(0)])),
                ('ack', models.BooleanField(default=False)),
                ('abort_on_NACK', models.BooleanField()),
                ('comments', models.TextField(blank=True)),
                ('packet_order', models.IntegerField(validators=[django.core.validators.MinValueValidator(0)])),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='TC_Sent_Packet',
            fields=[
                ('packet_id', models.AutoField(serialize=False, primary_key=True)),
                ('template_number', models.IntegerField()),
                ('service', models.CharField(max_length=5, choices=[(b'TVS', b'TVS'), (b'MMS', b'MMS'), (b'PMS', b'PMS'), (b'FMS', b'FMS'), (b'OBOSC', b'OBOSC'), (b'LDTS', b'LDTS'), (b'OBSRS', b'OBSRS')])),
                ('sub_service', models.PositiveSmallIntegerField(validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(15)])),
                ('apid', models.CharField(max_length=7, choices=[(b'COM', b'COM'), (b'BAE', b'BAE'), (b'CDMS', b'CDMS'), (b'SPEED', b'SPEED')])),
                ('app_data1', models.CharField(max_length=50, blank=True)),
                ('app_data2', models.CharField(max_length=50, blank=True)),
                ('app_data3', models.CharField(max_length=50, blank=True)),
                ('app_data', models.CharField(max_length=260, blank=True)),
                ('app_data_string', models.TextField(blank=True)),
                ('long_short', models.PositiveSmallIntegerField(validators=[django.core.validators.MaxValueValidator(1), django.core.validators.MinValueValidator(0)])),
                ('ack', models.BooleanField(default=False)),
                ('abort_on_NACK', models.BooleanField()),
                ('comments', models.TextField(blank=True)),
                ('packet_order', models.IntegerField(validators=[django.core.validators.MinValueValidator(0)])),
                ('packet_seq_count', models.IntegerField(validators=[django.core.validators.MinValueValidator(0)])),
                ('next_psc', models.IntegerField(validators=[django.core.validators.MinValueValidator(1)])),
                ('is_enabled', models.BooleanField(default=True)),
                ('is_retry_allowed', models.BooleanField(default=True)),
                ('is_resend_allowed', models.BooleanField(default=True)),
                ('sub_pass', models.PositiveSmallIntegerField(default=Telecommands.models.get_current_sub_pass, validators=[django.core.validators.MinValueValidator(1)])),
                ('send_datetime', models.DateTimeField(default=datetime.datetime.now)),
                ('resend_tries', models.IntegerField(default=0, validators=[django.core.validators.MaxValueValidator(20), django.core.validators.MinValueValidator(-1)])),
                ('resend_times', models.IntegerField(default=0, validators=[django.core.validators.MaxValueValidator(20), django.core.validators.MinValueValidator(-1)])),
                ('remarks', models.CharField(max_length=100, blank=True)),
                ('ack_L1', models.IntegerField(default=-1, validators=[django.core.validators.MinValueValidator(-1), django.core.validators.MaxValueValidator(4)])),
                ('ack_L2', models.NullBooleanField()),
                ('ack_L3', models.NullBooleanField()),
                ('ack_L4', models.NullBooleanField()),
                ('error_code', models.CharField(max_length=10, blank=True)),
                ('nack', models.NullBooleanField()),
                ('passing_slot', models.ForeignKey(related_name='pass_slot_sent', default=Telecommands.models.get_current_pass, to='Telecommands.Satellite_Pass')),
                ('send_by', models.ForeignKey(related_name='send_by', to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='TC_Template',
            fields=[
                ('template_name', models.CharField(max_length=50)),
                ('template_number', models.AutoField(serialize=False, primary_key=True)),
                ('to_display', models.BooleanField(default=True)),
                ('template_freq', models.IntegerField(default=0)),
                ('modification_time', models.DateTimeField(default=datetime.datetime.now)),
                ('created_by', models.ForeignKey(related_name='created_by', to=settings.AUTH_USER_MODEL)),
                ('modified_by', models.ForeignKey(related_name='modified_by', to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.AddField(
            model_name='long_beacon',
            name='passing_slot',
            field=models.ForeignKey(related_name='pass_slot_long_beacon', default=Telecommands.models.get_current_pass, to='Telecommands.Satellite_Pass'),
        ),
    ]

0002_auto_20161229_1325.py

from __future__ import unicode_literals

from django.db import models, migrations
import django.utils.timezone


class Migration(migrations.Migration):

    dependencies = [
        ('Telecommands', '0001_initial'),
    ]

    operations = [
        migrations.AddField(
            model_name='tc_sent_packet',
            name='error_status',
            field=models.CharField(default=b'Not yet received', max_length=300, blank=True),
        ),
        migrations.AlterField(
            model_name='long_beacon',
            name='recieved_on',
            field=models.DateTimeField(default=django.utils.timezone.now),
        ),
        migrations.AlterField(
            model_name='tc_sent_packet',
            name='send_datetime',
            field=models.DateTimeField(default=django.utils.timezone.now),
        ),
        migrations.AlterField(
            model_name='tc_template',
            name='modification_time',
            field=models.DateTimeField(default=django.utils.timezone.now),
        ),
    ]

0003_sent_tc_qm_validation

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
import django.utils.timezone


class Migration(migrations.Migration):

    dependencies = [
        ('Telecommands', '0002_auto_20161229_1325'),
    ]

    operations = [
        migrations.CreateModel(
            name='Sent_TC_QM_Validation',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('TC_ID', models.IntegerField(null=True)),
                ('TC_List_Name', models.CharField(max_length=50, blank=True)),
                ('Telecommand_Name', models.CharField(max_length=50, blank=True)),
                ('Table_Name', models.CharField(max_length=50, blank=True)),
                ('Parameter', models.CharField(max_length=50, blank=True)),
                ('Expected_Value_Min', models.CommaSeparatedIntegerField(max_length=50, null=True)),
                ('Expected_Value_Max', models.CommaSeparatedIntegerField(max_length=50, null=True)),
                ('Time_Stamp', models.DateTimeField(verbose_name=django.utils.timezone.now)),
                ('Received_Value', models.CommaSeparatedIntegerField(max_length=50, null=True)),
                ('Success', models.NullBooleanField()),
                ('Comments', models.CharField(max_length=50, blank=True)),
            ],
        ),
    ]
Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
Anisuki
  • 1
  • 2

1 Answers1

0

If you don't have db.sqlite3 file, then you've never migrated your models to the database.

At first try to run python manage.py makemigrations to create migrations and then run python manage.py migrate to apply these migrations.

Also replace your DATABASES settings.py variable to this:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}
curioushuman
  • 207
  • 3
  • 11
  • @Anisuki update your code please with your **models.py** file. And what is inside your migrations folder ? – curioushuman May 31 '22 at 10:24
  • I tried ```python manage.py makemigrations``` again but as always same error ```django.db.utils.OperationalError: no such table: Telecommands_satellite_pass ``` Updating code, please wait few min – Anisuki May 31 '22 at 10:25
  • @Anisuki I've updated the answer, try to perform the advice about `DATABASES` variable. – curioushuman May 31 '22 at 10:32
  • Tried, still same error. – Anisuki May 31 '22 at 10:35
  • @Anisuki okay, now I'm sure that your `db.sqlite3` file exists, you have to delete it. If there is no `db.sqlite3` file in your project root directory, then run the next command in your terminal ```sudo find ./* -name db.sqlite3``` from project root path. – curioushuman May 31 '22 at 10:47
  • I got this ```./db.sqlite3 ./MCS/db.sqlite3 ``` and now i had deleted both, removed all file in migrations (both telemetry and telecommand) except __init.py__. But still same error :/ – Anisuki May 31 '22 at 10:58
  • @Anisuki then I have no idea why this happens. Sure I can make a suggestion that the error is being raised because of old versions of python and django, but it's not reasonable, can you share your code to github ? – curioushuman May 31 '22 at 11:02
  • Hey, it might be because of your signal handlers, which could call some code before any migrations run. So if that code then imports any models, and the db is empty, it breaks before it gets a chance to run any migrations. I've written up an answer [here](https://stackoverflow.com/q/73786126/) – platelminto Sep 20 '22 at 12:03