torchbox / wagtail-headless-preview

Previews for headless Wagtail setups

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Unique constraint error in create_page_preview

johncarter-phntm opened this issue · comments

create_page_preview is calling get_or_create without passing the non-unique values as defaults. This leads to a unique constraint error, eg
django.db.utils.IntegrityError: UNIQUE constraint failed: wagtail_headless_preview_pagepreview.token if it's called twice when the signer returns the same value (eg if it's called twice in the same second).

# Note: Using get_or_create() instead of just create() to avoid unique constraint
# failures if preview is clicked multiple times
preview, _ = PagePreview.objects.get_or_create(
token=self.get_preview_signer().sign(identifier),
content_type=self.content_type,
content_json=self.to_json(),
)
return preview
def update_page_preview(self, token):
return PagePreview.objects.update_or_create(
token=token,
defaults={
"content_type": self.content_type,
"content_json": self.to_json(),
},
)

One solution would be pass defaults to get_or_create, but I think maybe it'd be better to call update_page_preview regardless?

Hi @johncarter-phntm,

Do you have a reliable way to reproduce this? My colleague reported that he was able to trigger this error in a way that would not seem to be caused by previews being created in rapid succession. I'm asking for more details, but here is how he described it:

  1. Edit a page with preview panel enabled
  2. Browse another section of the cms
  3. Go back to edit the page in step 1

@Scotchester in normal use, no, but my unit test in #35 reliably hits it. I only saw one real live occurrence of it in my app logs.

I think if you generated 2 previews of the same page with different JSON in the same second you'll hit it, due to use of TimestampSigner.