diff --git a/boards/forms.py b/boards/forms.py --- a/boards/forms.py +++ b/boards/forms.py @@ -22,8 +22,6 @@ LAST_LOGIN_TIME = 'last_login_time' TEXT_PLACEHOLDER = _('Type message here. Use formatting panel for more advanced usage.') TAGS_PLACEHOLDER = _('tag1 several_words_tag') -ERROR_IMAGE_DUPLICATE = _('Such image was already posted') - LABEL_TITLE = _('Title') LABEL_TEXT = _('Text') LABEL_TAG = _('Tag') @@ -149,10 +147,6 @@ class PostForm(NeboardForm): _('Image must be less than %s bytes') % str(board_settings.MAX_IMAGE_SIZE)) - image_hash = PostImage.get_hash(image) - if PostImage.objects.filter(hash=image_hash).exists(): - raise forms.ValidationError(ERROR_IMAGE_DUPLICATE) - return image def clean(self): diff --git a/boards/models/post.py b/boards/models/post.py --- a/boards/models/post.py +++ b/boards/models/post.py @@ -103,10 +103,17 @@ class PostManager(models.Manager): post, post.poster_ip)) if image: - post_image = PostImage.objects.create(image=image) + # Try to find existing image. If it exists, assign it to the post + # instead of createing the new one + image_hash = PostImage.get_hash(image) + existing = PostImage.objects.filter(hash=image_hash) + if len(existing) > 0: + post_image = existing[0] + else: + post_image = PostImage.objects.create(image=image) + logger.info('Created new image #{} for post #{}'.format( + post_image.id, post.id)) post.images.add(post_image) - logger.info('Created image #{} for post #{}'.format( - post_image.id, post.id)) thread.replies.add(post) list(map(thread.add_tag, tags)) @@ -352,7 +359,10 @@ class Post(models.Model, Viewable): thread with all posts is deleted. """ - self.images.all().delete() + for image in self.images.all(): + image_refs_count = Post.objects.filter(images__in=[image]).count() + if image_refs_count == 1: + image.delete() if self.is_opening(): self.get_thread().delete()