artem
artem

Reputation: 16777

django.db.utils.OperationalError after removing migrations & makemigrations

I have deleted all migrations in the project, deleted the database and trying to re-create migrations with manage.py makemigrations command. But I'm getting the error:

Traceback (most recent call last):
  File "/Applications/PyCharm.app/Contents/helpers/pycharm/django_manage.py", line 41, in <module>
    run_module(manage_file, None, '__main__', True)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 176, in run_module
    fname, loader, pkg_name)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 82, in _run_module_code
    mod_name, mod_fname, mod_loader, pkg_name)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 72, in _run_code
    exec code in run_globals
  File "/Users/rankor/src/python/web/Auction/Auction/manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line
    utility.execute()
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/core/management/__init__.py", line 342, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/core/management/base.py", line 348, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/core/management/base.py", line 398, in execute
    self.check()
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/core/management/base.py", line 426, in check
    include_deployment_checks=include_deployment_checks,
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/core/checks/registry.py", line 75, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/core/checks/urls.py", line 10, in check_url_config
    return check_resolver(resolver)
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/core/checks/urls.py", line 19, in check_resolver
    for pattern in resolver.url_patterns:
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/core/urlresolvers.py", line 417, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/core/urlresolvers.py", line 410, in urlconf_module
    return import_module(self.urlconf_name)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/Users/rankor/src/python/web/Auction/Auction/Auction/urls.py", line 14, in <module>
    url(r'^orders/', include('orders.urls', namespace='orders')),
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/conf/urls/__init__.py", line 52, in include
    urlconf_module = import_module(urlconf_module)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/Users/rankor/src/python/web/Auction/Auction/orders/urls.py", line 3, in <module>
    from orders.views import CreateOrderView, OrdersView, OrderView
  File "/Users/rankor/src/python/web/Auction/Auction/orders/views.py", line 7, in <module>
    from orders.forms import OrderForm
  File "/Users/rankor/src/python/web/Auction/Auction/orders/forms.py", line 47, in <module>
    class OrderForm(ModelForm):
  File "/Users/rankor/src/python/web/Auction/Auction/orders/forms.py", line 60, in OrderForm
    widget=forms.Select, queryset=OrderCategory.objects.filter(parent__isnull=False).order_by('ordering'))
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/forms/models.py", line 1142, in __init__
    self.queryset = queryset
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/forms/models.py", line 1168, in _set_queryset
    self.widget.choices = self.choices
  File "/Users/rankor/src/python/web/Auction/Auction/orders/forms.py", line 16, in _get_choices
    if not self.queryset:
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/db/models/query.py", line 266, in __nonzero__
    return type(self).__bool__(self)
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/db/models/query.py", line 262, in __bool__
    self._fetch_all()
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/db/models/query.py", line 1074, in _fetch_all
    self._result_cache = list(self.iterator())
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/db/models/query.py", line 52, in __iter__
    results = compiler.execute_sql()
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 852, in execute_sql
    cursor.execute(sql, params)
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/db/utils.py", line 95, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 323, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: orders_ordercategory

OrderForm:

class OrderForm(ModelForm):
    """
    Order form
    """

    class Meta:
        model = Order
        fields = ('city', 'category', 'title', 'min_price', 'max_price', 'description', 'delivery_type', 'valid_to')

    city = forms.ModelChoiceField(
            widget=forms.Select, queryset=City.objects.filter(country__code='RU').order_by('name'))

    category = CategoryChoiceField(
            widget=forms.Select, queryset=OrderCategory.objects.filter(parent__isnull=False).order_by('ordering'))

    valid_to = forms.DateField(widget=SelectDateWidget)

class GroupedModelChoiceField(forms.ModelChoiceField):
    def optgroup_from_instance(self, obj):
        return ""

    def __choice_from_instance__(self, obj):
        return obj.id, self.label_from_instance(obj)

    def _get_choices(self):
        if not self.queryset:
            return []

        all_choices = []
        if self.empty_label:
            current_optgroup = ""
            current_optgroup_choices = [("", self.empty_label)]
        else:
            current_optgroup = self.optgroup_from_instance(self.queryset[0])
            current_optgroup_choices = []

        for item in self.queryset:
            optgroup_from_instance = self.optgroup_from_instance(item)
            if current_optgroup != optgroup_from_instance:
                all_choices.append((current_optgroup, current_optgroup_choices))
                current_optgroup_choices = []
                current_optgroup = optgroup_from_instance
            current_optgroup_choices.append(self.__choice_from_instance__(item))

        all_choices.append((current_optgroup, current_optgroup_choices))

        return all_choices

    choices = property(_get_choices, forms.ChoiceField._set_choices)


class CategoryChoiceField(GroupedModelChoiceField):
    def optgroup_from_instance(self, obj):
        return obj.parent.title

Why and how to fix it?

P.S. Django 1.9, python 2.7, OS X.

Upvotes: 1

Views: 701

Answers (1)

Gabriel Pichot
Gabriel Pichot

Reputation: 2493

Look at the stacktrace.

During the warm up process, Django imports all models and urls.

You should move queryset initialization to the init method of your OrderForm.

For a more general note, and to answer Lorenzo. In all cases you want to move fields querysets initialisation to the init method of your form or moved them to your views. Why? Actually, when Django is started, it can import some of your forms, the form class is built and the same happen with your field-class attributes. As a result, the queryset is fetched directly, once and for all, when importing your form and stays constant as long as you do not reload the server, so if you ever add data to your OrderCategory it will never appear in your select widget.

The "workaround" is to move queryset initialisation to the init method of the form.

In your case :

class OrderForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(OrderForm, self).__init__(*args, **kwargs)
        self.fields['city'].queryset = City.objects.filter(country__code='RU').order_by('name')
        self.fields['category'].queryset = OrderCategory.objects.filter(parent__isnull=False).order_by('ordering')
    class Meta:
       #...
    # ... fields definition

See Fields which handle relationships for relative Django documentation.

Upvotes: 5

Related Questions