python: no se puede publicar la página en django-cms debido a “IntegrityError: el valor de la clave duplicada viola la restricción única\

En mi sitio web de django-cms tengo algunos problemas al publicar páginas a través de la interfaz de administración. Debajo del stacktrace:

    DEBUG 2013-06-07 14:09:31,562 util 32222 140056576640768 (0.000) SELECT DISTINCT "menus_cachekey"."key" FROM "menus_cachekey" WHERE "menus_cachekey"."site" = 1 ; args=(1,)
DEBUG 2013-06-07 14:09:31,565 util 32222 140056576640768 (0.000) DELETE FROM "menus_cachekey" WHERE "menus_cachekey"."site" = 1 ; args=(1,)
DEBUG 2013-06-07 14:09:31,570 util 32222 140056576640768 (0.001) INSERT INTO "cms_page" ("created_by", "changed_by", "parent_id", "creation_date", "changed_date", "publication_date", "publication_end_date", "in_navigation", "soft_root", "reverse_id", "navigation_extenders", "published", "template", "site_id", "login_required", "limit_visibility_in_menu", "level", "lft", "rght", "tree_id", "publisher_is_draft", "publisher_public_id", "publisher_state") VALUES (E'roberto', E'roberto', NULL, E'2013-06-07 12:09:31.567872+00:00', E'2013-06-07 12:09:31.567989+00:00', E'2013-06-07 12:09:26.553334+00:00', NULL, false, false, NULL, NULL, true, E'unicms/departments_and_groups/department_detail.html', 1, false, NULL, 0, 1, 2, 9, false, 9, 0) RETURNING "cms_page"."id"; args=(u'roberto', u'roberto', None, u'2013-06-07 12:09:31.567872+00:00', u'2013-06-07 12:09:31.567989+00:00', u'2013-06-07 12:09:26.553334+00:00', None, False, False, None, None, True, u'unicms/departments_and_groups/department_detail.html', 1, False, None, 0, 1, 2, 9, False, 9, 0)
ERROR 2013-06-07 14:09:31,571 base 32222 140056576640768 Internal Server Error: /admin/cms/page/9/change-status/
Traceback (most recent call last):
  File "/home/roberto/.virtualenvs/ve_news2_app/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 115, in get_response
    response = callback(request, *callback_args, **callback_kwargs)
  File "/home/roberto/.virtualenvs/ve_news2_app/local/lib/python2.7/site-packages/django/utils/decorators.py", line 91, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "/home/roberto/.virtualenvs/ve_news2_app/local/lib/python2.7/site-packages/django/views/decorators/cache.py", line 89, in _wrapped_view_func
    response = view_func(request, *args, **kwargs)
  File "/home/roberto/.virtualenvs/ve_news2_app/local/lib/python2.7/site-packages/django/contrib/admin/sites.py", line 202, in inner
    return view(request, *args, **kwargs)
  File "/home/roberto/.virtualenvs/ve_news2_app/local/lib/python2.7/site-packages/django/utils/decorators.py", line 25, in _wrapper
    return bound_func(*args, **kwargs)
  File "/home/roberto/.virtualenvs/ve_news2_app/local/lib/python2.7/site-packages/django/views/decorators/http.py", line 41, in inner
    return func(request, *args, **kwargs)
  File "/home/roberto/.virtualenvs/ve_news2_app/local/lib/python2.7/site-packages/django/utils/decorators.py", line 21, in bound_func
    return func(self, *args2, **kwargs2)
  File "/home/roberto/.virtualenvs/ve_news2_app/local/lib/python2.7/site-packages/cms/admin/pageadmin.py", line 1062, in change_status
    success = method()
  File "/home/roberto/.virtualenvs/ve_news2_app/local/lib/python2.7/site-packages/cms/models/pagemodel.py", line 419, in publish
    public_page.save()
  File "/home/roberto/.virtualenvs/ve_news2_app/local/lib/python2.7/site-packages/cms/models/pagemodel.py", line 367, in save
    super(Page, self).save(**kwargs)
  File "/home/roberto/.virtualenvs/ve_news2_app/local/lib/python2.7/site-packages/mptt/models.py", line 696, in save
    super(MPTTModel, self).save(*args, **kwargs)
  File "/home/roberto/.virtualenvs/ve_news2_app/local/lib/python2.7/site-packages/django/db/models/base.py", line 546, in save
    force_update=force_update, update_fields=update_fields)
  File "/home/roberto/.virtualenvs/ve_news2_app/local/lib/python2.7/site-packages/cms/models/pagemodel.py", line 384, in save_base
    ret = super(Page, self).save_base(*args, **kwargs)
  File "/home/roberto/.virtualenvs/ve_news2_app/local/lib/python2.7/site-packages/django/db/models/base.py", line 650, in save_base
    result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw)
  File "/home/roberto/.virtualenvs/ve_news2_app/local/lib/python2.7/site-packages/django/db/models/manager.py", line 215, in _insert
    return insert_query(self.model, objs, fields, **kwargs)
  File "/home/roberto/.virtualenvs/ve_news2_app/local/lib/python2.7/site-packages/django/db/models/query.py", line 1661, in insert_query
    return query.get_compiler(using=using).execute_sql(return_id)
  File "/home/roberto/.virtualenvs/ve_news2_app/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 937, in execute_sql
    cursor.execute(sql, params)
  File "/home/roberto/.virtualenvs/ve_news2_app/local/lib/python2.7/site-packages/django/db/backends/util.py", line 41, in execute
    return self.cursor.execute(sql, params)
  File "/home/roberto/.virtualenvs/ve_news2_app/local/lib/python2.7/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 56, in execute
    six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
  File "/home/roberto/.virtualenvs/ve_news2_app/local/lib/python2.7/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 54, in execute
    return self.cursor.execute(query, args)
IntegrityError: duplicate key value violates unique constraint "cms_page_publisher_public_id_key"

El modelo de departamento es bastante simple.

class Department(models.Model):
    research_area = models.ManyToManyField('research_area.ResearchArea', blank=True,
                                           related_name='departments')  # many-to-many
    products = models.ManyToManyField('products_activities.Product', blank=True, related_name="departments")
    employees = models.ManyToManyField('staff.Person', through='department.PersonDepartmentMembership',
                                       related_name='departments')  # TODO WARNINGS
    research_groups = models.ManyToManyField('group.Group', blank=True, related_name='departments',
                                             through="department.GroupDepartmentMembership")
    page = models.OneToOneField(Page, blank=True, related_name='department', null=True)


    name = models.CharField(_('department name'), max_length=50, default=_('Department name'))
    description = models.TextField(_('department description'))
    logo = models.ImageField(upload_to='img/departments')
    address = models.CharField(_('office address'), max_length=255)
    post_address = models.CharField(_('post address'), max_length=255)
    telephone = PhoneNumberField(blank=True, null=True)
    fax = PhoneNumberField(blank=True, null=True)
    email = models.EmailField()

    class Meta:
        permissions = (
            ('view_department', _('View department')),
        )

    def __unicode__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('pages-details-by-slug', kwargs={'slug': self.page.get_slug('en')})

No todas las páginas están afectadas por este problema. En mi cms he configurado un sistema automático de creación de páginas. Cuando el usuario crea un departamento, se configura una nueva página.

@receiver(post_save, sender=Department)
def _on_save_department_create_link_to_page(sender, instance, created, **kwargs):
    from cms.api import assign_user_to_page, add_plugin, publish_page
    if created:  # create department Page
        from cms.api import create_page

        instance.page = create_page(
            title=instance.name,
            language='en',
            published=False,
            template=settings.CMS_TEMPLATE_DEPARTMENT[0],
        )

        # add some plugins...

        editors = instance.employees.filter(cmsuser__groups__name__exact='web')
        for e in editors:
            assign_user_to_page(instance.page, e)
        instance.page.save()

He encontrado en Internet el número some blog article que apunta que puede deberse a sucesivas migraciones hacia el sur. Casi no lo dudo, ya que tengo el error sin aplicar ninguna migración de datos también.

Cualquier comentario será muy apreciado! Gracias por adelantado 🙂

Mejor respuesta
Debido al cambio en la forma en que se ejecuta la moderación al actualizar django-cms, deberá ejecutar:

python manage.py cms moderator on

Ver http://docs.django-cms.org/en/2.4.0/advanced/cli.html#moderation-commands para más información.

Si aún estás luchando con algunas de las páginas que aún dan ese error de restricción, necesitarás abrir un shell de django:

python manage.py dbshell

Y luego eliminar el problema con SQL

delete from cms_page where publisher_public_id=79;

Por favor indique la dirección original:python: no se puede publicar la página en django-cms debido a “IntegrityError: el valor de la clave duplicada viola la restricción única\ - Código de registro