Files
game-cards-poker-design/backend/apps/templates/views.py

59 lines
1.7 KiB
Python
Raw Normal View History

from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from .models import CardTemplate
from apps.projects.models import LibraryAsset
def _template_to_dict(t):
return {
'id': t.id,
'name': t.name,
'description': t.description,
'preview_image': t.preview_image.url if t.preview_image else None,
'theme_id': t.theme_id,
'colors': {
'spade': t.color_spade,
'heart': t.color_heart,
'club': t.color_club,
'diamond': t.color_diamond,
'background': t.color_background,
},
'design_override': t.design_override or {},
}
def _template_with_preview(t):
"""附加 library 中 theme_id 对应的素材预览(前端可以画一组小图)"""
out = _template_to_dict(t)
libs = LibraryAsset.objects.filter(theme_id=t.theme_id)
out['library'] = [
{
'id': lib.id,
'role': lib.role,
'role_name': lib.role_name,
'label': lib.label,
'file_url': f'/media/{lib.file_path}',
}
for lib in libs
]
return out
@api_view(['GET'])
def template_list(request):
"""获取所有模板列表(含每个模板的 theme 预览)"""
templates = CardTemplate.objects.all()
data = [_template_with_preview(t) for t in templates]
return Response(data)
@api_view(['GET'])
def template_detail(request, pk):
"""获取模板详情"""
try:
template = CardTemplate.objects.get(pk=pk)
except CardTemplate.DoesNotExist:
return Response({'error': 'Template not found'}, status=status.HTTP_404_NOT_FOUND)
return Response(_template_with_preview(template))