duplicate key value violates unique constraint "django_site_pkey" #3506
-
Hello Guys, I've been running a django project based on cookie-cutter-django for a while. Now, I'm trying to run 2 domains with the same project, so same DB and apps, but different urls and allowed_hosts. I am currently setting this up on pythonanywhere and in the meantime, I wanted to already add the second domain as a Site instance, in order to be able to use the Sites framework down the line. But I got a duplicate key values error when trying to do that. The first Site instance has been created by the original cookie cutter migration. Did you already experience this behaviour and is there an obvious answer to that ? Thanks a lot in advance !! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Can you expand a bit on how you're creating this? What have you tried, etc... Is it through the admin, a migration or via the Django console? Here is how the original site is created: As you can see, we providing the ID primary key explicitly. I think it's a common issue with Django where the database sequence gets out of sync in this case. These posts explain how to fix the problem:
An update to a sequence isn't rolled back when the transaction failed, so your error probably bumped the sequence value and it should work if you try again. |
Beta Was this translation helpful? Give feedback.
-
Actually, it worked the second time I tried, I don't know why. |
Beta Was this translation helpful? Give feedback.
Can you expand a bit on how you're creating this? What have you tried, etc... Is it through the admin, a migration or via the Django console?
Here is how the original site is created:
cookiecutter-django/{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/contrib/sites/migrations/0003_set_site_domain_and_name.py
Lines 13 to 19 in a808aca
As you can see, we providing the ID primary key explicitly. I think it's a common issue with Django where the database sequen…