Skip to content

Commit

Permalink
chore(feat): add fix
Browse files Browse the repository at this point in the history
  • Loading branch information
ndu committed Dec 18, 2024
1 parent b7e0fa5 commit 1a74fd3
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 18 deletions.
10 changes: 4 additions & 6 deletions server/apps/research/models/article.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,16 +145,14 @@ def save(self, *args, **kwargs):
if self.scheduled_publish_time and self.status == 'draft' and timezone.now() >= self.scheduled_publish_time:
self.status = 'ready'

if self.thumb and not hasattr(self.thumb, 'public_id'):
super().save(*args, **kwargs)
elif self.thumb and hasattr(self.thumb, 'public_id'):
if self.thumb and hasattr(self.thumb, 'public_id'):
try:
if not self.thumb.public_id:
raise ValidationError("Failed to upload image to Cloudinary")
except Exception as e:
raise ValidationError(f"Image upload failed: {str(e)}")
else:
super().save(*args, **kwargs)
raise ValidationError(f"Image upload failed: {str(e)}") from e

super().save(*args, **kwargs)

def generate_unique_slug(self):
"""Generate a unique slug for the article."""
Expand Down
18 changes: 8 additions & 10 deletions server/apps/research/serializers/article_serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,18 @@
from .category_serializer import CategorySerializer
from django.conf import settings

def get_cloudinary_url(public_id):
if not public_id:
return None
return f"{settings.CLOUDINARY_DOMAIN}/{public_id}"

class RelatedArticleSerializer(serializers.ModelSerializer):
authors = AuthorSerializer(many=True)
categories = CategorySerializer(many=True)
thumb = serializers.SerializerMethodField()

def get_thumb(self, obj):
if obj.thumb:
return f"https://res.cloudinary.com/dc2iz5j1c/{obj.thumb}"
return None
return get_cloudinary_url(obj.thumb)

class Meta:
model = Article
Expand All @@ -38,9 +40,7 @@ class ArticleListSerializer(serializers.ModelSerializer):
thumb = serializers.SerializerMethodField()

def get_thumb(self, obj):
if obj.thumb:
return f"https://res.cloudinary.com/dc2iz5j1c/{obj.thumb}"
return None
return get_cloudinary_url(obj.thumb)

def get_related_articles(self, obj):
related = obj.get_related_articles()
Expand Down Expand Up @@ -70,9 +70,7 @@ class ArticleSerializer(serializers.ModelSerializer):
thumb = serializers.SerializerMethodField()

def get_thumb(self, obj):
if obj.thumb:
return f"{settings.CLOUDINARY_DOMAIN}/{obj.thumb}"
return None
return get_cloudinary_url(obj.thumb)

def get_related_articles(self, obj):
related = obj.get_related_articles()
Expand Down Expand Up @@ -192,4 +190,4 @@ def update(self, instance: Article, validated_data: dict) -> Article:
return instance
except Exception as e:
logging.error(f"Error updating article: {str(e)}")
raise serializers.ValidationError("An error occurred while updating the article.")
raise serializers.ValidationError("Error updating article.") from e
12 changes: 10 additions & 2 deletions server/apps/research/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
import cloudinary.uploader
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.core.exceptions import ValidationError


# Set up logging
Expand Down Expand Up @@ -125,14 +127,20 @@ def is_valid_uuid(self, value):
except ValueError:
return False

@csrf_exempt
@require_http_methods(["POST"])
def tinymce_upload_image(request):
if request.method == "POST" and request.FILES:
try:
file = request.FILES['file']
if not file.content_type.startswith('image/'):
raise ValidationError("Only image files are allowed")
if file.size > 5 * 1024 * 1024:
raise ValidationError("File size too large")
upload_data = cloudinary.uploader.upload(
file,
folder='article_content'
folder='article_content',
allowed_formats=['png', 'jpg', 'jpeg', 'gif'],
resource_type="image"
)
return JsonResponse({
'location': upload_data['secure_url']
Expand Down

0 comments on commit 1a74fd3

Please sign in to comment.