Getting django.db.utils.ProgrammingError: (1146, "Table 'password_management.accounts_workspace' doesn't exist")

Hi there,

I am trying to make migrations by running the following command:

python manage.py makemigrations

But, I am getting the below error:

django.db.utils.ProgrammingError: (1146, "Table 'password_management.accounts_workspace' doesn't exist")

I am using MySQL Database named as password_management.

Earlier my app was working fine with all the user migrations and stuff. When I made this new Model Workspace, I am getting the above mentioned error.

Full Error Details:

Traceback (most recent call last):
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\db\backends\utils.py", line 89, in _execute
    return self.cursor.execute(sql, params)
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\db\backends\mysql\base.py", line 75, in execute
    return self.cursor.execute(query, args)
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\MySQLdb\cursors.py", line 206, in execute
    res = self._query(query)
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\MySQLdb\cursors.py", line 319, in _query
    db.query(q)
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\MySQLdb\connections.py", line 254, in query
    _mysql.connection.query(self, query)
MySQLdb._exceptions.ProgrammingError: (1146, "Table 'password_management.accounts_workspace' doesn't exist")

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "D:\Projects\meistery\projects\pricing_password_management_poc\inviteandresetpass\manage.py", line 22, in <module>
    main()
  File "D:\Projects\meistery\projects\pricing_password_management_poc\inviteandresetpass\manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line
    utility.execute()
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\core\management\__init__.py", line 440, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\core\management\base.py", line 414, in run_from_argv
    self.execute(*args, **cmd_options)
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\core\management\base.py", line 455, in execute
    self.check()
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\core\management\base.py", line 487, in check
    all_issues = checks.run_checks(
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\core\checks\registry.py", line 88, in run_checks
    new_errors = check(app_configs=app_configs, databases=databases)
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\core\checks\urls.py", line 42, in check_url_namespaces_unique
    all_namespaces = _load_all_namespaces(resolver)
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\core\checks\urls.py", line 61, in _load_all_namespaces
    url_patterns = getattr(resolver, "url_patterns", [])
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\utils\functional.py", line 49, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\urls\resolvers.py", line 696, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\utils\functional.py", line 49, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\urls\resolvers.py", line 689, in urlconf_module
    return import_module(self.urlconf_name)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "D:\Projects\meistery\projects\pricing_password_management_poc\inviteandresetpass\inviteandresetpass\urls.py", line 21, in <module>
    path("accounts/", include("apps.accounts.urls")),  # URLs of Login/Registration System
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\urls\conf.py", line 38, in include
    urlconf_module = import_module(urlconf_module)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "D:\Projects\meistery\projects\pricing_password_management_poc\inviteandresetpass\apps\accounts\urls.py", line 4, in <module>
    from .views import (
  File "D:\Projects\meistery\projects\pricing_password_management_poc\inviteandresetpass\apps\accounts\views.py", line 16, in <module>
    from .forms import (
  File "D:\Projects\meistery\projects\pricing_password_management_poc\inviteandresetpass\apps\accounts\forms.py", line 14, in <module>
    for i in range(len(workspaces)):
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\db\models\query.py", line 302, in __len__
    self._fetch_all()
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\db\models\query.py", line 1507, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\db\models\query.py", line 57, in __iter__
    results = compiler.execute_sql(
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\db\models\sql\compiler.py", line 1361, in execute_sql
    cursor.execute(sql, params)
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\db\backends\utils.py", line 103, in execute
    return super().execute(sql, params)
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\db\backends\utils.py", line 67, in execute
    return self._execute_with_wrappers(
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\db\backends\utils.py", line 80, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    with self.db.wrap_database_errors:
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\db\utils.py", line 91, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\db\backends\utils.py", line 89, in _execute
    return self.cursor.execute(sql, params)
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\db\backends\mysql\base.py", line 75, in execute
    return self.cursor.execute(query, args)
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\MySQLdb\cursors.py", line 206, in execute
    res = self._query(query)
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\MySQLdb\cursors.py", line 319, in _query
    db.query(q)
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\MySQLdb\connections.py", line 254, in query
    _mysql.connection.query(self, query)
django.db.utils.ProgrammingError: (1146, "Table 'password_management.accounts_workspace' doesn't exist")

My Workspace model is below:

class Workspace(models.Model):
    name = models.CharField(max_length=254)
    name_slug = models.SlugField(editable=False)
    admin = models.ForeignKey(User, on_delete=models.CASCADE, default=None)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self) -> str:
        """
        Returns a string to as an instance name
        """
        return (self.name)

    def save(self, *args, **kwargs):
        if self.name:
            try:
                group = Group.objects.get(name=self.name)
                group.delete()
            except Exception as ex:
                print(ex)
            
            permissions = Permission.objects.all

            for p in permissions:
                if p.name.endswith(self.name):
                    p.delete()

        super(Workspace, self).save(*args, **kwargs)

        self.name_slug = slugify(self.name)

        workspace_group = Group.objects.create(
            name="manage-" + self.name_slug
        )

        content_type = ContentType.objects.get_for_model(Workspace)

        permissions = []
        permissions.append(
            Permission.objects.create(
                codename='can_remove_from_workspace_%s' % self.name_slug,
                name='Can Remove User From Workspace %s' % self.name,
                content_type=content_type,
            )
        )
        permissions.append(
            Permission.objects.create(
                codename='can_add_to_workspace_%s' % self.name_slug,
                name='Can Add User To Workspace %s' % self.name,
                content_type=content_type,
            )
        )
        permissions.append(
            Permission.objects.create(
                codename='can_view_from_workspace_%s' % self.name_slug,
                name='Can View User From Workspace %s' % self.name,
                content_type=content_type,
            )
        )

        workspace_group.permissions.set(permissions)

        super(Workspace, self).save(*args, **kwargs)

    def make_admin(self, user):
        user.add_workspace(self)

        self.admin = user
        self.save()

    def remove_admin(self):
        self.admin = None
        self.save()

    def invite_workspace_user(self, user, invite_form_data):
        workspace = invite_form_data["workspace"]
        
        invitation = Invitation.objects.create(
            created_by = user,
            invitee_email = invite_form_data["invitee_email"],
            invitee_first_name = invite_form_data["invitee_first_name"],
            invitee_last_name = invite_form_data["invitee_last_name"]
        )
        
        invitation.send_invite_user_email(workspace)

    def get_by_name(self, name):
        try:
            return self.objects.get(name=name)
        except:
            return None

In admins.py I have:

from .models import Workspace

admin.site.register(Workspace)

In forms.py I have:

from .models import Workspace

WORKSPACES_CHOICES = []
    
workspaces = Workspace.objects.all()

for i in range(len(workspaces)):
    WORKSPACES_CHOICES.append(tuple((str(i + 1), workspaces[i].name)))

WORKSPACES_CHOICES = tuple(WORKSPACES_CHOICES)

class InviteUserByAdminForm(forms.ModelForm):
    workspaces = forms.MultipleChoiceField(
        widget=forms.CheckboxSelectMultiple,
        choices=WORKSPACES_CHOICES
    )

    class Meta:
        model = Invitation
        fields = (
            "invitee_first_name",
            "invitee_last_name",
            "sent_to",
            "workspaces",
        )

I have already tried all the solutions mentioned in this thread at stackoverflow. But, none of them worked for me.

Anyone can tell me what’s wrong?

If your indentation in what you’ve posted is accurate, you’re attempting to access the Workspace model at the module level. It’s being evaluated at the time the module is being imported, which means it’s trying to access it when you run makemigration - before the table exists.

You should never write any code that accesses a model outside of a class or function. (There are other potential side effects from doing so beyond this issue with migrations. It’s just a bad idea overall.)

@KenWhitesell I want to include the WORKSPACES_CHOICES inside the InviteUserByAdminForm, if I should not write it outside of a class, then where should I put this code? Inside Workspace Model by defining a new function for this?

Read the docs on choices. Choices can refer to a callable.

Define a function in your form class to retrieve those values, and specify that callable in the choices parameter for the field.

OK, I did this:

class InviteUserByAdminForm(forms.ModelForm):
    workspaces = forms.MultipleChoiceField(
        widget=forms.CheckboxSelectMultiple,
        choices=self.workspaces_choices()
    )

    def workspaces_choices(self):
        workspaces = Workspace.objects.all()

        WORKSPACES_CHOICES = []

        for i in range(len(workspaces)):
            WORKSPACES_CHOICES.append(tuple((str(i + 1), workspaces[i].name)))

        return tuple(WORKSPACES_CHOICES)

    class Meta:
        model = Invitation
        fields = (
            "invitee_first_name",
            "invitee_last_name",
            "sent_to",
            "workspaces",
        )

But, I am getting following error on this line of code workspaces = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=self.workspaces_choices()):

"self" is not definedPylance

You pass the callable as the option - you don’t call the function.

workspaces_choices() calls the function and returns the value returned by that function.

workspaces_choices is the callable that refers to that function.

Side note - you probably want the Workspaces pk to be the value returned by the select box, not the arbitrary index created by the iterator.

OK, I changed:

choices=self.workspaces_choices()

to:

choices=self.workspaces_choices

But I am still getting the same error, that is:

"self" is not defined

Full Error Details are:

Traceback (most recent call last):
  File "D:\Projects\meistery\projects\pricing_password_management_poc\inviteandresetpass\manage.py", line 22, in <module>
    main()
  File "D:\Projects\meistery\projects\pricing_password_management_poc\inviteandresetpass\manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line
    utility.execute()
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\core\management\__init__.py", line 440, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\core\management\base.py", line 414, in run_from_argv
    self.execute(*args, **cmd_options)
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\core\management\base.py", line 455, in execute
    self.check()
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\core\management\base.py", line 487, in check
    all_issues = checks.run_checks(
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\core\checks\registry.py", line 88, in run_checks
    new_errors = check(app_configs=app_configs, databases=databases)
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\core\checks\urls.py", line 42, in check_url_namespaces_unique
    all_namespaces = _load_all_namespaces(resolver)
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\core\checks\urls.py", line 61, in _load_all_namespaces
    url_patterns = getattr(resolver, "url_patterns", [])
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\utils\functional.py", line 49, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\urls\resolvers.py", line 696, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\utils\functional.py", line 49, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\urls\resolvers.py", line 689, in urlconf_module
    return import_module(self.urlconf_name)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "D:\Projects\meistery\projects\pricing_password_management_poc\inviteandresetpass\inviteandresetpass\urls.py", line 21, in <module>
    path("accounts/", include("apps.accounts.urls")),  # URLs of Login/Registration System
  File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\urls\conf.py", line 38, in include
    urlconf_module = import_module(urlconf_module)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "D:\Projects\meistery\projects\pricing_password_management_poc\inviteandresetpass\apps\accounts\urls.py", line 4, in <module>
    from .views import (
  File "D:\Projects\meistery\projects\pricing_password_management_poc\inviteandresetpass\apps\accounts\views.py", line 16, in <module>
    from .forms import (
  File "D:\Projects\meistery\projects\pricing_password_management_poc\inviteandresetpass\apps\accounts\forms.py", line 40, in <module>
    class InviteUserByAdminForm(forms.ModelForm):
  File "D:\Projects\meistery\projects\pricing_password_management_poc\inviteandresetpass\apps\accounts\forms.py", line 52, in InviteUserByAdminForm
    choices=self.workspaces_choices
NameError: name 'self' is not defined

Ah, right. This needs to be accessed at the class level.

Add the @staticmethod decorator to the function, remove the self parameter in the function signature, and specify the reference as InviteUserByAdminForm.workspace_choices

Or, you could move it to be a function outside the class, and continue to reference it directly as workspace_choices (still without any parameters).

1 Like

@KenWhitesell moving the function out of the class did the trick. Thanks a lot.

Not an issue but still want to ask, why my forms.py has dull color?
image

Is that a VSCode panel? If so, it would have something to do with the theme you’re using. I don’t use that type of theme, so I don’t know what would cause that. Either way it’s a VSCode issue and not related to Django.

1 Like