python3 manage.py миграция исключений

Я новичок в django 1.7 и python3. Я использую ОСХ. Поскольку я следил за документацией по django 1.7 в Интернете,

Я попытался

python3 manage.py migrate

и это привело

Operations to perform:
Apply all migrations: auth, contenttypes, sessions, admin
Running migrations:
No migrations to apply.
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/contrib/contenttypes/models.py", line 44, in get_for_model
ct = self._get_from_cache(opts)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/contrib/contenttypes/models.py", line 34, in _get_from_cache
return self.__class__._cache[self.db][key]
KeyError: 'default'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/backends/mysql/base.py", line 128, in execute
return self.cursor.execute(query, args)
  File "/Users/NAME/Library/Python/3.4/lib/python/site-packages/MySQLdb/cursors.py", line 184, in execute
self.errorhandler(self, exc, value)
  File "/Users/NAME/Library/Python/3.4/lib/python/site-packages/MySQLdb/connections.py", line 37, in defaulterrorhandler
raise errorvalue
  File "/Users/NAME/Library/Python/3.4/lib/python/site-packages/MySQLdb/cursors.py", line 171, in execute
r = self._query(query)
  File "/Users/NAME/Library/Python/3.4/lib/python/site-packages/MySQLdb/cursors.py", line 330, in _query
rowcount = self._do_query(q)
  File "/Users/NAME/Library/Python/3.4/lib/python/site-packages/MySQLdb/cursors.py", line 294, in _do_query
db.query(q)
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s AND `django_content_type`.`model` = %s) LIMIT 21' at line 1")

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

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/contrib/contenttypes/models.py", line 50, in get_for_model
defaults={'name': smart_text(opts.verbose_name_raw)},
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/models/manager.py", line 92, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/models/query.py", line 422, in get_or_create
    return self.get(**lookup), False
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/models/query.py", line 351, in get
num = len(clone)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/models/query.py", line 122, in __len__
self._fetch_all()
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/models/query.py", line 966, in _fetch_all
self._result_cache = list(self.iterator())
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/models/query.py", line 265, in iterator
for row in compiler.results_iter():
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/models/sql/compiler.py", line 700, in results_iter
for rows in self.execute_sql(MULTI):
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/models/sql/compiler.py", line 786, in execute_sql
cursor.execute(sql, params)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/backends/utils.py", line 81, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/utils/six.py", line 549, in reraise
raise value.with_traceback(tb)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/backends/mysql/base.py", line 128, in execute
return self.cursor.execute(query, args)
  File "/Users/NAME/Library/Python/3.4/lib/python/site-packages/MySQLdb/cursors.py", line 184, in execute
self.errorhandler(self, exc, value)
  File "/Users/NAME/Library/Python/3.4/lib/python/site-packages/MySQLdb/connections.py", line 37, in defaulterrorhandler
raise errorvalue
  File "/Users/NAME/Library/Python/3.4/lib/python/site-packages/MySQLdb/cursors.py", line 171, in execute
r = self._query(query)
  File "/Users/NAME/Library/Python/3.4/lib/python/site-packages/MySQLdb/cursors.py", line 330, in _query
rowcount = self._do_query(q)
  File "/Users/NAME/Library/Python/3.4/lib/python/site-packages/MySQLdb/cursors.py", line 294, in _do_query
    db.query(q)
django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s AND `django_content_type`.`model` = %s) LIMIT 21' at line 1")

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/core/management/__init__.py", line 377, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **options.__dict__)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/core/management/base.py", line 338, in execute
output = self.handle(*args, **options)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 164, in handle
emit_post_migrate_signal(created_models, self.verbosity, self.interactive, connection.alias)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/core/management/sql.py", line 268, in emit_post_migrate_signal
using=db)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/dispatch/dispatcher.py", line 198, in send
response = receiver(signal=self, sender=sender, **named)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/contrib/auth/management/__init__.py", line 83, in create_permissions
ctype = ContentType.objects.db_manager(using).get_for_model(klass)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/contrib/contenttypes/models.py", line 58, in get_for_model
" is migrated before trying to migrate apps individually."
RuntimeError: Error creating new content types. Please make sure contenttypes is migrated before trying to migrate apps individually.`

Я не знаю, что это значит, и я уверен, что это неправильно. Миграция прошла успешно? Пожалуйста помоги. Спасибо

Вот мой /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/contrib/contenttypes/models.py

from __future__ import unicode_literals

from django.apps import apps
from django.db import models
from django.db.utils import OperationalError, ProgrammingError
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import smart_text, force_text
from django.utils.encoding import python_2_unicode_compatible


class ContentTypeManager(models.Manager):

    # Cache to avoid re-looking up ContentType objects all over the place.
    # This cache is shared by all the get_for_* methods.
    _cache = {}

    def get_by_natural_key(self, app_label, model):
        try:
            ct = self.__class__._cache[self.db][(app_label, model)]
        except KeyError:
            ct = self.get(app_label=app_label, model=model)
            self._add_to_cache(self.db, ct)
        return ct

    def _get_opts(self, model, for_concrete_model):
        if for_concrete_model:
            model = model._meta.concrete_model
        elif model._deferred:
            model = model._meta.proxy_for_model
        return model._meta

    def _get_from_cache(self, opts):
        key = (opts.app_label, opts.model_name)
        return self.__class__._cache[self.db][key]

    def get_for_model(self, model, for_concrete_model=True):
        """
        Returns the ContentType object for a given model, creating the
        ContentType if necessary. Lookups are cached so that subsequent lookups
        for the same model don't hit the database.
        """
        opts = self._get_opts(model, for_concrete_model)
        try:
            ct = self._get_from_cache(opts)
        except KeyError:
            try:
                ct, created = self.get_or_create(
                    app_label=opts.app_label,
                    model=opts.model_name,
                    defaults={'name': smart_text(opts.verbose_name_raw)},
                )
            except (OperationalError, ProgrammingError):
                # It's possible to migrate a single app before contenttypes,
                # as it's not a required initial dependency (it's contrib!)
                # Have a nice error for this.
                raise RuntimeError(
                    "Error creating new content types. Please make sure contenttypes" +
                    " is migrated before trying to migrate apps individually."
                )
            self._add_to_cache(self.db, ct)

        return ct

    def get_for_models(self, *models, **kwargs):
        """
        Given *models, returns a dictionary mapping {model: content_type}.
        """
        for_concrete_models = kwargs.pop('for_concrete_models', True)
        # Final results
        results = {}
        # models that aren't already in the cache
        needed_app_labels = set()
        needed_models = set()
        needed_opts = set()
        for model in models:
            opts = self._get_opts(model, for_concrete_models)
            try:
                ct = self._get_from_cache(opts)
            except KeyError:
                needed_app_labels.add(opts.app_label)
                needed_models.add(opts.model_name)
                needed_opts.add(opts)
            else:
                results[model] = ct
        if needed_opts:
            cts = self.filter(
                app_label__in=needed_app_labels,
                model__in=needed_models
            )
            for ct in cts:
                model = ct.model_class()
                if model._meta in needed_opts:
                    results[model] = ct
                    needed_opts.remove(model._meta)
                self._add_to_cache(self.db, ct)
        for opts in needed_opts:
            # These weren't in the cache, or the DB, create them.
            ct = self.create(
                app_label=opts.app_label,
                model=opts.model_name,
                name=smart_text(opts.verbose_name_raw),
            )
            self._add_to_cache(self.db, ct)
            results[ct.model_class()] = ct
        return results

    def get_for_id(self, id):
        """
        Lookup a ContentType by ID. Uses the same shared cache as get_for_model
        (though ContentTypes are obviously not created on-the-fly by get_by_id).
        """
        try:
            ct = self.__class__._cache[self.db][id]
        except KeyError:
            # This could raise a DoesNotExist; that's correct behavior and will
            # make sure that only correct ctypes get stored in the cache dict.
            ct = self.get(pk=id)
            self._add_to_cache(self.db, ct)
        return ct

    def clear_cache(self):
        """
        Clear out the content-type cache. This needs to happen during database
        flushes to prevent caching of "stale" content type IDs (see
        django.contrib.contenttypes.management.update_contenttypes for where
        this gets called).
        """
        self.__class__._cache.clear()

    def _add_to_cache(self, using, ct):
        """Insert a ContentType into the cache."""
        # Note it's possible for ContentType objects to be stale; model_class() will return None.
        # Hence, there is no reliance on model._meta.app_label here, just using the model fields instead.
        key = (ct.app_label, ct.model)
        self.__class__._cache.setdefault(using, {})[key] = ct
        self.__class__._cache.setdefault(using, {})[ct.id] = ct


@python_2_unicode_compatible
class ContentType(models.Model):
    name = models.CharField(max_length=100)
    app_label = models.CharField(max_length=100)
    model = models.CharField(_('python model class name'), max_length=100)
    objects = ContentTypeManager()

    class Meta:
        verbose_name = _('content type')
        verbose_name_plural = _('content types')
        db_table = 'django_content_type'
        ordering = ('name',)
        unique_together = (('app_label', 'model'),)

    def __str__(self):
        # self.name is deprecated in favor of using model's verbose_name, which
        # can be translated. Formal deprecation is delayed until we have DB
        # migration to be able to remove the field from the database along with
        # the attribute.
        #
        # We return self.name only when users have changed its value from the
        # initial verbose_name_raw and might rely on it.
        model = self.model_class()
        if not model or self.name != model._meta.verbose_name_raw:
            return self.name
        else:
            return force_text(model._meta.verbose_name)

    def model_class(self):
        "Returns the Python model class for this type of content."
        try:
            return apps.get_model(self.app_label, self.model)
        except LookupError:
            return None

    def get_object_for_this_type(self, **kwargs):
        """
        Returns an object of this type for the keyword arguments given.
        Basically, this is a proxy around this object_type's get_object() model
        method. The ObjectNotExist exception, if thrown, will not be caught,
        so code that calls this method should catch it.
        """
        return self.model_class()._base_manager.using(self._state.db).get(**kwargs)

    def get_all_objects_for_this_type(self, **kwargs):
        """
        Returns all objects of this type for the keyword arguments given.
        """
        return self.model_class()._base_manager.using(self._state.db).filter(**kwargs)

    def natural_key(self):
        return (self.app_label, self.model)

person Artorias    schedule 24.10.2014    source источник


Ответы (2)


Я считаю, что это зависимость от mysql. После того, как я перешел на postgresql, все решилось. Я обнаружил, что соединитель python с mysql работает только до python 3.3, и я использую python3.4. Вероятно, поэтому я не смог найти коннектор для mysql и python 3.4.

person Artorias    schedule 31.10.2014
comment
Теперь вы можете использовать pypi.python.org/pypi/mysqlclient, у меня была та же проблема, что и вы, но если вы посмотрите документы django для mysql, они также рекомендуют это - person Dennis; 20.11.2014
comment
Спасибо. Я проверю это. :) - person Artorias; 24.11.2014

Я предполагаю, что могут быть некоторые проблемы с зависимостями.

Вместо запуска:

python3 manage.py migrate

попробуйте с:

python manage.py makemigrations yourapp
python manage.py migrate

если это не работает, используйте:

python manage.py syncdb --all
person Sasa    schedule 25.10.2014
comment
Я добавил models.py, но я не уверен, где найти эту ошибку оператора SQL. Это в курсорах.py? Спасибо. - person Artorias; 26.10.2014
comment
Может быть, но я вижу, что это не ваш код, все это находится под сайт-пакетами. Я предполагаю, что здесь проблема в некоторых зависимостях. Не могли бы вы создать свою базу данных с помощью: python manage.py syncdb --all. После этого попробуйте миграцию. - person Sasa; 26.10.2014
comment
Я считаю, что это и о зависимостях тоже. Единственное, что я изменил, это settings.py. БАЗЫ ДАННЫХ = { 'по умолчанию': { 'ДВИГАТЕЛЬ': 'django.db.backends.mysql', 'ИМЯ': 'DJANGO3', 'ПОЛЬЗОВАТЕЛЬ': 'root', 'ПАРОЛЬ': '', 'ХОСТ': ' ', 'PORT': '', } } django 1.7 отлично работает с python. однако, когда я перешел на python3, это не удалось. python manage.py syncdb работает, а python3 manage.py syncdb — нет. Я также сначала попробовал python3 manage.py makemigrations. не работает. Я слежу за этим сайтом: docs.djangoproject.com/en/1.7/intro/tutorial01 - person Artorias; 26.10.2014
comment
почему вы форсируете python3, когда работа с python работает правильно? - person Sasa; 26.10.2014
comment
Я заметил, что ваш учебник, кроме команды schemamigration. Пожалуйста, убедитесь, что вы запустили эту команду перед миграцией - person Sasa; 26.10.2014
comment
причина, по которой я использую python3, заключается в том, что я действительно хочу попробовать версию python 3.x с django 1.7 вместо использования python 2.7. Я думаю, что рано или поздно перейду на python 3.x. Почему не сейчас? Разве я не должен использовать python3.x? - person Artorias; 26.10.2014
comment
видя, что OP относится к django 1.7, вы используете команды управления для юга, а не миграции django. - person Llanilek; 06.02.2015