djangocms-snippet icon indicating copy to clipboard operation
djangocms-snippet copied to clipboard

Updating an existing Snippet results in invalid error message

Open bartTC opened this issue 1 year ago • 6 comments

When you update an existing snippet, the admin will throw an error message "A Snippet with this name already exists."

Looks like the issue is the clean method, it literally checks if that snippet exists already. This makes sense for new snippets, but not for updating existing ones.

https://github.com/django-cms/djangocms-snippet/blob/master/src/djangocms_snippet/forms.py#L37-L46

Steps to reproduce:

  • Go to Admin > Snippets > Snippet
  • Add a new Snippet
  • Add any name and HTML content
  • Hit "Save and continue editing"
  • Hit "Save and continue editing" again

bartTC avatar Jan 21 '25 11:01 bartTC

I fixed this on my side now by monkeypatching the clean method.

class BetterSnippetForm(SnippetForm):
    def clean(self) -> dict:
        return self.cleaned_data

I think it's better to rely on a unique=True property in the name/slug Model field rather than trying to fix it within the clean method. Though that might not be backwards compatible.

bartTC avatar Jan 21 '25 11:01 bartTC

@bartTC Thank you for raising this issue.

Restricting this on DB-Level will not work since snipets can be versioned in principle and there might be several versions of the same snippet.

Looking at the source, I come to think that the lines https://github.com/django-cms/djangocms-snippet/blob/62bb317e68f1274ee8b1091466604ce763d9a130/src/djangocms_snippet/forms.py#L39-L40 might be the issue. I believe the exclude should always be applied to the queryset. Am I right in assuming that you do not use versioned snippets?

fsbraun avatar Jan 21 '25 12:01 fsbraun

That's correct, I'm not using versioning. It's used in a Django CMS 3.x environment.

bartTC avatar Jan 21 '25 12:01 bartTC

Would you mind testing the branch #177 to see if it works for you?

fsbraun avatar Jan 21 '25 12:01 fsbraun

I'll check, might take until Friday though.

bartTC avatar Jan 22 '25 13:01 bartTC

@fsbraun this is fixing it! Thank you 👍

bartTC avatar Jan 27 '25 16:01 bartTC