【问题标题】:KeyError: ('profiles', 'talk') - How do I resolve?KeyError: ('profiles', 'talk') - 我该如何解决?
【发布时间】:2015-07-26 08:37:27
【问题描述】:

这里是新手。 尝试使用 Django 和 Postgres db 构建应用程序。我目前正在努力迁移,遇到此错误“KeyError: ('profiles', 'talk')”

这是我尝试迁移后命令行中的错误:

(myvenv) Abbys-iMac:talks abbyhumphreys$ python manage.py migrate
/Users/abbyhumphreys/talks/myvenv/lib/python3.4/site-packages/django/contrib/sites/models.py:78: RemovedInDjango19Warning: Model class django.contrib.sites.models.Site doesn't declare an explicit app_label and either isn't in an application in INSTALLED_APPS or else was imported before its application was loaded. This will no longer be supported in Django 1.9.
class Site(models.Model):

System check identified some issues:

WARNINGS:
profiles.Profile.user: (fields.W342) Setting unique=True on a ForeignKey has the same effect as using a OneToOneField.
HINT: ForeignKey(unique=True) is usually better served by a OneToOneField.
registration.RegistrationProfile.user: (fields.W342) Setting unique=True on a   ForeignKey has the same effect as using a OneToOneField.
HINT: ForeignKey(unique=True) is usually better served by a OneToOneField.
Operations to perform:
Synchronize unmigrated apps: staticfiles, registration, humanize, messages
Apply all migrations: profiles, auth, sessions, admin, contenttypes
Synchronizing apps without migrations:
Creating tables...
    Running deferred SQL...
    Installing custom SQL...
Running migrations:
    Rendering model states...Traceback (most recent call last):
    File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
    File "/Users/abbyhumphreys/talks/myvenv/lib/python3.4/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
    File "/Users/abbyhumphreys/talks/myvenv/lib/python3.4/site-packages/django/core/management/__init__.py", line 330, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
    File "/Users/abbyhumphreys/talks/myvenv/lib/python3.4/site-packages/django/core/management/base.py", line 390, in run_from_argv
self.execute(*args, **cmd_options)
    File "/Users/abbyhumphreys/talks/myvenv/lib/python3.4/site-packages/django/core/management/base.py", line 441, in execute
output = self.handle(*args, **options)
    File "/Users/abbyhumphreys/talks/myvenv/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 221, in handle
executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
    File "/Users/abbyhumphreys/talks/myvenv/lib/python3.4/site-packages/django/db/migrations/executor.py", line 104, in migrate
state = migration.mutate_state(state, preserve=do_run)
    File "/Users/abbyhumphreys/talks/myvenv/lib/python3.4/site-packages/django/db/migrations/migration.py", line 83, in mutate_state
operation.state_forwards(self.app_label, new_state)
    File "/Users/abbyhumphreys/talks/myvenv/lib/python3.4/site-packages/django/db/migrations/operations/fields.py", line 256, in state_forwards
for n, f in state.models[app_label, self.model_name_lower].fields
KeyError: ('profiles', 'talk')

这是我的models.py:

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

class Profile(models.Model):
    name = models.CharField(max_length=255)
    sname = models.CharField(max_length=255, blank=True, null=True)
    phone = models.CharField(max_length=255, blank=True, null=True)
    mobile = models.CharField(max_length=255, blank=True, null=True)
    email = models.EmailField(max_length=254, blank=True, null=True)
    address = models.TextField(blank=True, null=True)
    notes = models.TextField()
    slug = models.SlugField(unique=True)
    user = models.ForeignKey(User, unique=True, blank=True, null=True, related_name="users")

class Talk(models.Model):
    talk_no = models.CharField(max_length=255, blank=True, null=True)
    talk_name = models.CharField(max_length=255, blank=True, null=True)
    slug = models.SlugField(unique=True)

class Congregation(models.Model):
    cong_name = models.CharField(max_length=255, blank=True, null=True)
    meeting_time = models.CharField(max_length=255, blank=True, null=True)
    cong_address = models.TextField(blank=True, null=True)
    cong_phone = models.CharField(max_length=255, blank=True, null=True)
    slug = models.SlugField(unique=True)

这是我的views.py:

from django.contrib.auth.decorators import login_required
from django.http import Http404
from django.shortcuts import render, render_to_response, redirect
from django.template import RequestContext
from profiles.forms import ProfileForm, TalkForm, CongForm
from profiles.models import Profile, Talk, Congregation
from django.template.defaultfilters import slugify

def index(request):
    ids = Profile.objects.all()
    return render(request, 'index.html',{'ids': ids,})

def about(request):

    return render(request, 'about.html',)

def contact(request):

    return render(request, 'contact.html',)

def profile_detail(request, slug):
    #grab the object...
    profile=Profile.objects.get(slug=slug)
    #and pass to the template
    return render(request,'ids/profile_detail.html', {
        'profile': profile,
    })

@login_required
def edit_profile(request, slug):
    profile = Profile.objects.get(slug=slug)
    if profile.user != request.user:
        raise Http404

    form_class = ProfileForm

    if request.method == 'POST':
        form = form_class(data=request.POST, instance=profile)
        if form.is_valid():
            form.save()
            return redirect('profile_detail', slug=profile.slug)
    else:
        form = form_class(instance=profile)
    return render(request, 'ids/edit_profile.html', {'profile': profile, 'form': form, })

def create_profile(request):
    form_class = ProfileForm

    if request.method == 'POST':
        form=form_class(request.POST)
        if form.is_valid():
            profile=form.save(commit=False)
            profile.user = request.user
            profile.slug = slugify(profile.name)
            profile.save()
            slug = slugify(name)
        return redirect('profile_detail', slug=profile.slug)
    else:
        form=form_class()
    return render(request, 'ids/create_profile.html', {'form': form,})

def browse_by_name(request, initial=None):
    if initial:
        ids = Profile.objects.filter(name__istartswith=initial).order_by('name')
    else:
        ids = Profile.objects.all().order_by('name')

    return render_to_response('search/search.html', {'ids': ids, 'initial': initial,}, context_instance=RequestContext(request))

def talk_detail(request, slug):
    #grab the object...
    talk=Talk.objects.get(slug=slug)
    #and pass to the template
    return render(request,'ids/talk_detail.html', {
        'talk': talk,
    })

@login_required
def edit_talk(request, slug):
    talk = Talk.objects.get(slug=slug)
    if profile.user != request.user:
        raise Http404

    form_class = TalkForm

    if request.method == 'POST':
        form = form_class(data=request.POST, instance=talk)
        if form.is_valid():
            form.save()
            return redirect('talk_detail', slug=slug.slug)
    else:
        form = form_class(instance=talk)
    return render(request, 'ids/edit_talk.html', {'talk': talk, 'form': form,   })

def create_talk(request):
    form_class = TalkForm

    if request.method == 'POST':
        form=form_class(request.POST)
        if form.is_valid():
            talk=form.save(commit=False)
            profile.user = request.user
            talk.slug = slugify(talk.talk_no)
            talk.save()
            slug = slugify(talk_no)
        return redirect('talk_detail', slug=talk.slug)
    else:
        form=form_class()
    return render(request, 'ids/create_talk.html', {'form': form,})

def cong_detail(request, slug):
    #grab the object...
    cong=Congregation.objects.get(slug=slug)
    #and pass to the template
    return render(request,'ids/cong_detail.html', {
        'cong': cong,
    })

@login_required
def edit_cong(request, slug):
    cong = Congregation.objects.get(slug=slug)
    if profile.user != request.user:
        raise Http404

    form_class = CongForm

    if request.method == 'POST':
        form = form_class(data=request.POST, instance=cong)
        if form.is_valid():
            form.save()
            return redirect('cong_detail', slug=cong.slug)
    else:
        form = form_class(instance=cong)
    return render(request, 'ids/edit_cong.html', {'cong': cong, 'form': form, })

def create_cong(request):
    form_class = CongForm

    if request.method == 'POST':
        form=form_class(request.POST)
        if form.is_valid():
            cong=form.save(commit=False)
            profile.user = request.user
            cong.slug = slugify(cong.cong_name)
            cong.save()
            slug = slugify(cong_name)
        return redirect('cong_detail', slug=cong.slug)
    else:
        form=form_class()
    return render(request, 'ids/create_cong.html', {'form': form,})

这是我的 url.py

from django.contrib import admin
from profiles.backends import MyRegistrationView
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.views.generic import TemplateView, RedirectView
from django.contrib.auth.views import password_reset, password_reset_done,  password_reset_confirm, password_reset_complete

urlpatterns = patterns('',
    url(r'^$', 'profiles.views.index', name='home'),
    url(r'^about/$', TemplateView.as_view(template_name='about.html'), name='about'),
    url(r'^contact/$', TemplateView.as_view(template_name='contact.html'), name='contact'),

    url(r'^ids/$', RedirectView.as_view(pattern_name='browse')),
    url(r'^ids/(?P<slug>[-\w]+)/$', 'profiles.views.profile_detail', name='profile_detail'),
    url(r'^ids/(?P<slug>[-\w]+)/edit/$', 'profiles.views.edit_profile', name='edit_profile'),

    url(r'^ids/(?P<slug>[-\w]+)/$', 'profiles.views.talk_detail', name='talk_detail'),
    url(r'^ids/(?P<slug>[-\w]+)/edit/$', 'profiles.views.edit_talk', name='edit_talk'),

    url(r'^ids/(?P<slug>[-\w]+)/$', 'profiles.views.cong_detail', name='cong_detail'),
    url(r'^ids/(?P<slug>[-\w]+)/edit/$', 'profiles.views.edit_cong', name='edit_cong'),

    url(r'^browse/$', RedirectView.as_view(pattern_name='browse')),
    url(r'^browse/name/$','profiles.views.browse_by_name', name='browse'),
    url(r'^browse/name/(?P<initial>[-\w]+)/$', 'profiles.views.browse_by_name', name='browse_by_name'),

    url(r'^accounts/password/reset/$', password_reset, 
    {'template_name': 'registration/password_reset_form.html'}, 
    name="password_reset"),
    url(r'^accounts/password/reset/done/$', 
    password_reset_done, 
    {'template_name': 'registration/password_reset_done.html'}, 
    name="password_reset_done"),
    url(r'^accounts/password/reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
    password_reset_confirm, 
    {'template_name': 'registration/password_reset_confirm.html'}, 
    name="password_reset_confirm"),
    url(r'^accounts/password/done/$', password_reset_complete,
    {'template_name': 'registration/password_reset_complete.html'},
    name="password_reset_complete"),

    url(r'^accounts/register/$', MyRegistrationView.as_view(), name='registration_register'),
    url(r'^accounts/create_profile/$', 'profiles.views.create_profile', name='registration_create_profile'),
    url(r'^accounts/create_talk/$', 'profiles.views.create_talk', name='registration_create_talk'),
    url(r'^accounts/create_cong/$', 'profiles.views.create_cong', name='registration_create_cong'),

    url(r'^accounts/', include('registration.backends.default.urls')),
    url(r'^admin/', include(admin.site.urls)),
)

不确定我提供的信息是否过多或过少,但作为新手,我不知道错误的含义或您可能需要什么信息才能弄清楚!

提前感谢您在解决此问题方面的帮助以及您耐心查看我所有糟糕的代码! :-s

【问题讨论】:

  • 你能解决这个问题吗?我遇到了同样的问题,现在卡住了:(
  • 我有一个类似的错误,它适用于我从migrations文件夹中删除所有自动生成的文件(所以除了__init__.py之外的所有文件)然后运行makemigrationsmigrate来制作它们再次。

标签: django django-models migrate django-migrations


【解决方案1】:

当您执行以下步骤时会发生这种情况:

  1. 运行

迁移应用名称

并且由于错误而停止执行。

  1. 你再次运行它,但这次它出错了,因为新表 已创建。

  2. 您编辑迁移文件,删除代码 部分创建表,然后再次运行迁移。

我的解决方法是,我没有删除 CreateModel,而是移动了 到之前的迁移文件。

【讨论】:

  • 运行迁移两次是无害的。此外,我不认为新手(即 OP)应该搞乱迁移。
  • 谢谢!将与先前创建的数据库相关的部分代码放入其中的想法非常巧妙。
【解决方案2】:

你最好在这个问题中显示你的迁移文件的代码,因为问题可能就在那里。

可能是您没有在其中创建名为 talk 的模型的迁移文件。

可以通过将talk 模型的创建添加到其中一个迁移文件中来解决问题。

【讨论】:

    【解决方案3】:

    我在编辑迁移文件时遇到了这个错误,但没有注意到我在创建该字段的模型之前为该字段放置了一个 AddField()。也许可以帮助某人。

    【讨论】:

    • 是的。我认为要点应该是:除非您知道自己在做什么,否则不要编辑迁移。
    【解决方案4】:

    我已经构建了自己的“wheel-package”(您可以使用pip install &lt;filename&gt; 安装的东西),在部署它并转到./manage.py migrate 之后,遇到了这个问题。

    这就是我发现问题所在的方式:

    在我的 dev-box 上,我删除了所有迁移,运行 makemigrations 并构建了一个新包。在将新包部署到测试盒并从头开始删除数据库后,migrate 仍会尝试应用它不应该知道的旧迁移文件。

    我发现构建过程不知何故没有清理迁移文件夹(在我的情况下为/&lt;app&gt;/build/lib/&lt;app&gt;/migrations/),该文件夹包含早期尝试弄乱模型的旧迁移文件。所以有多个版本的0001* 等,Django 尝试将它们全部应用。

    我删除了/build-目录并让脚本从头开始创建它。

    【讨论】:

      【解决方案5】:

      这里的新手也遇到了同样的问题,尽管我很感激这个帖子早就冷了。我遵循最新的 Django 2.1 教程,然后尝试将我的应用程序迁移到单独的“Django-app”包中。

      我不断收到源自 state.models[app_label, self.model_name_lower].fields 的 KeyError

      @Chris 上面的建议很有帮助。我正在使用 Mac OS High Sierra,所以我去了我的 ~/.virtualenvs/env/lib/python3.7/site-packages 并删除了自原始安装以来我创建的所有内容,包括我之前的应用程序版本'd 将其打包为 Django-app。

      它仍然没有工作,所以我发现还需要一个步骤。我在 ~/Library/Caches/pip/wheels 中发现了各种垃圾,我已将其删除。我还从我的 mySQL 数据库中删除了 Django 数据库。

      然后我创建了一个新的 Django 超级用户;重新进行迁移并运行它们。

      现在效果很好。

      希望这可以帮助像我这样非常沮丧的菜鸟。

      【讨论】:

        【解决方案6】:

        关键错误的原因是迁移计划没有为您正在修改的模型加载模型状态。 为了让计划加载该模型,它需要在迁移树的某处找到 CreateModel 指令(迁移树是指在遍历迁移的“依赖项”部分时构建的树)。

        如果该树永远不会导致您的模型使用 CreateModel 语句进行迁移,那么它将不在计划中。

        添加一个指向包含 CreateModel 指令的依赖项到有问题的迁移,事情应该会顺利进行。

        【讨论】:

          【解决方案7】:

          当我的一项迁移未成功执行时,我收到此错误。

          要重现问题,请在您的 django 应用程序中执行以下操作:

          • 禁用除无法迁移的模块之外的所有模块。
          • 请与./manage.py showmigrations 核对您的所有迁移是否已应用。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-05-25
            • 2021-03-22
            • 2023-01-03
            • 1970-01-01
            • 2019-05-10
            • 2021-08-20
            相关资源
            最近更新 更多