Skip to content

Commit

Permalink
prevent creating duplicate URLs on edit
Browse files Browse the repository at this point in the history
  • Loading branch information
sissbruecker committed Sep 24, 2024
1 parent 7b405c0 commit 04bfc7b
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
16 changes: 16 additions & 0 deletions bookmarks/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,22 @@ def has_notes(self):
self.instance and self.instance.notes
)

def clean(self):
cleaned_data = super().clean()
url = cleaned_data.get("url")

if self.instance.pk and url:
# Ensure there is no existing Bookmark with the same URL
existing_bookmark = (
Bookmark.objects.filter(url=url, owner=self.instance.owner)
.exclude(pk=self.instance.pk)
.first()
)
if existing_bookmark:
self.add_error("url", "A bookmark with this URL already exists.")

return cleaned_data


class BookmarkSearch:
SORT_ADDED_ASC = "added_asc"
Expand Down
36 changes: 36 additions & 0 deletions bookmarks/tests/test_bookmark_edit_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,42 @@ def test_should_prefill_bookmark_form_fields(self):
html,
)

def test_should_prevent_changing_url_to_existing_url_for_same_owner(self):
edited_bookmark = self.setup_bookmark(url="http://example.com/edited")
existing_bookmark = self.setup_bookmark(url="http://example.com/existing")

form_data = self.create_form_data(
{"id": edited_bookmark.id, "url": existing_bookmark.url}
)
response = self.client.post(
reverse("bookmarks:edit", args=[edited_bookmark.id]), form_data
)

self.assertEqual(response.status_code, 422)
self.assertInHTML(
"<li>A bookmark with this URL already exists.</li>",
response.content.decode(),
)
edited_bookmark.refresh_from_db()
self.assertNotEqual(edited_bookmark.url, existing_bookmark.url)

def test_should_allow_changing_url_to_existing_url_for_different_owner(self):
edited_bookmark = self.setup_bookmark(url="http://example.com/edited")
existing_bookmark = self.setup_bookmark(
url="http://example.com/existing", user=User.objects.create_user("other")
)

form_data = self.create_form_data(
{"id": edited_bookmark.id, "url": existing_bookmark.url}
)
response = self.client.post(
reverse("bookmarks:edit", args=[edited_bookmark.id]), form_data
)

self.assertEqual(response.status_code, 302)
edited_bookmark.refresh_from_db()
self.assertEqual(edited_bookmark.url, existing_bookmark.url)

def test_should_redirect_to_return_url(self):
bookmark = self.setup_bookmark()
form_data = self.create_form_data()
Expand Down

0 comments on commit 04bfc7b

Please sign in to comment.