Django: ValueError: поиск невозможен для модели, на которую ссылается полевая учетная запись. Пользовательский интерфейс: auth.User

Получение этой ошибки при запуске python manage.py migrate:

ValueError: сбой поиска для модели, на которую ссылается полевая учетная запись. UserSourceProxy.user: auth.User

Шаги, которые я сделал:

1. Создан проект и добавлено новое приложение:

$ django-admin.py startproject djdev
$ cd djdev
$ python manage.py startapp account

2. Я добавил новое приложение в INSTALLED_APPS в djdev/settings.py:

...
    'django.contrib.staticfiles',
    'account',
)
...

3. Создал новый класс UserProfile в account/models.py:

from django.db import models
from django.contrib.auth.models import User

class UserProfile(models.Model):
    """
    User Profile having one-to-one relations with User
    """
    class Meta:
        db_table = 'user_profile'
        ordering = ['id']

    user = models.OneToOneField(User, db_column='id_user', related_name='profile')

    mobile_no = models.CharField('Mobile no.', db_column='contact_no_home', max_length=16, blank=True, null=True)
    address_line_1 = models.CharField('Address Line 1', db_column='contact_address_line_1_home', max_length=140, blank=True, null=True)
    address_line_2 = models.CharField('Address Line 2', db_column='contact_address_line_2_home', max_length=140, blank=True, null=True)

    office_mobile_no = models.CharField('Mobile no.', db_column='contact_no_office', max_length=16, blank=True, null=True)
    office_address_line_1 = models.CharField('Address Line 1', db_column='contact_address_line_1_office', max_length=140, blank=True, null=True)
    office_address_line_2 = models.CharField('Address Line 2', db_column='contact_address_line_2_office', max_length=140, blank=True, null=True)

    about = models.TextField('About me', blank=True, null=True)
    note = models.CharField('Note', max_length=255, blank=True, null=True)

    def __unicode__(self):
        return self.user.name

4. Начало миграции:

$ python manage.py makemigrations account
$ python manage.py migrate

После выполнения последней команды python manage.py migrate я получаю эту ошибку:

Operations to perform:
  Synchronize unmigrated apps: (none)
  Apply all migrations: admin, contenttypes, account, auth, sessions
Synchronizing apps without migrations:
  Creating tables...
  Installing custom SQL...
  Installing indexes...
Running migrations:
  Applying account.0001_initial...Traceback (most recent call last):
  File "./manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/home/vinay/python_webapps/django-trunk/django/core/management/__init__.py", line 427, in execute_from_command_line
    utility.execute()
  File "/home/vinay/python_webapps/django-trunk/django/core/management/__init__.py", line 419, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/vinay/python_webapps/django-trunk/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/home/vinay/python_webapps/django-trunk/django/core/management/base.py", line 337, in execute
    output = self.handle(*args, **options)
  File "/home/vinay/python_webapps/django-trunk/django/core/management/commands/migrate.py", line 146, in handle
    executor.migrate(targets, plan, fake=options.get("fake", False))
  File "/home/vinay/python_webapps/django-trunk/django/db/migrations/executor.py", line 62, in migrate
    self.apply_migration(migration, fake=fake)
  File "/home/vinay/python_webapps/django-trunk/django/db/migrations/executor.py", line 90, in apply_migration
    if self.detect_soft_applied(migration):
  File "/home/vinay/python_webapps/django-trunk/django/db/migrations/executor.py", line 134, in detect_soft_applied
    apps = project_state.render()
  File "/home/vinay/python_webapps/django-trunk/django/db/migrations/state.py", line 83, in render
    model=lookup_model
ValueError: Lookup failed for model referenced by field account.UserProfile.user: auth.User

ПРИМЕЧАНИЕ. Версия Django, используемая мной: 1.8.dev20140507130401

Ответы

Ответ 1

Это уже исправлено в главной ветке.

Исправлено в commits:

Вы можете установить его до создания правильной версии:

pip install https://github.com/django/django/zipball/master

Test

models.py

from django.db import models
from django.contrib.auth.models import User

class Test(models.Model):
  user = models.OneToOneField(User)

Результаты

[__env] $ ./manage.py makemigrations
  Migrations for 'data':
  0001_initial.py:
    - Create model Test
[__env] $ ./manage.py migrate
  Operations to perform:
  Synchronize unmigrated apps: admin, contenttypes, auth, sessions
    (... ommited ...)
  Running migrations:
  Applying data.0001_initial... OK

Ответ 2

Я прочитал комментарий выше, предлагая добавить только последнюю строку в список зависимостей (('contenttypes',' __first__')), но мне пришлось добавить последние два, чтобы исправить проблему. Это может быть очевидно для тех, кто лучше разбирается в инструменте makemigrations в Django, но я новичок в этом, и это было не для меня.

Мой последний список зависимостей файлов миграции, изначально выдавший ту же ошибку...

dependencies = [
    ('myapp', '0006_auto_20150209_0324'),
    (b'auth', b'__first__'),
    (b'contenttypes', b'__first__'),
]

Ответ 3

Я нашел другое решение, которое также отлично работает.

См. решение от rockallite.wulf @ https://code.djangoproject.com/ticket/22488

Просто добавьте соответствующую зависимость в файл миграции, например:

dependencies = [
        (b'advperm', b'0001_initial'),
        (b'auth', b'__first__'),
        (b'contenttypes', b'__first__'),  # Add this line
]