daren/example_usage.py

153 lines
4.8 KiB
Python
Raw Permalink Normal View History

2025-05-23 19:08:40 +08:00
"""
CreatorProfile头像字段使用示例
演示如何在Django项目中使用avatar字段来处理本地图片和外部URL
"""
from django.core.files.uploadedfile import SimpleUploadedFile
from apps.daren_detail.models import CreatorProfile
from django.conf import settings
import os
def create_creator_with_local_avatar():
"""创建一个使用本地图片作为头像的创作者"""
# 方式1通过Django admin或表单上传图片
# 用户上传图片后Django会自动保存到 MEDIA_ROOT/avatars/ 目录
creator = CreatorProfile.objects.create(
name="张三",
category="Beauty & Personal Care",
followers=10000
)
# 假设有一个图片文件
# with open('path/to/image.jpg', 'rb') as f:
# creator.avatar.save('zhang_san.jpg', f)
print(f"创作者: {creator.name}")
print(f"头像URL: {creator.get_avatar_url()}")
return creator
def create_creator_with_external_url():
"""创建一个使用外部URL作为头像的创作者"""
creator = CreatorProfile.objects.create(
name="李四",
avatar_url="https://example.com/avatar.jpg",
category="Fashion Accessories",
followers=20000
)
print(f"创作者: {creator.name}")
print(f"头像URL: {creator.get_avatar_url()}")
return creator
def create_creator_with_both():
"""创建一个既有本地图片又有外部URL的创作者优先使用本地图片"""
creator = CreatorProfile.objects.create(
name="王五",
avatar_url="https://example.com/backup-avatar.jpg",
category="Sports & Outdoor",
followers=30000
)
# 如果后来上传了本地图片,会优先使用本地图片
# creator.avatar.save('wang_wu.jpg', image_file)
print(f"创作者: {creator.name}")
print(f"头像URL: {creator.get_avatar_url()}")
return creator
# API使用示例
def api_response_example():
"""API响应示例"""
# 在视图中使用序列化器
from apps.daren_detail.serializers import CreatorProfileSerializer
from django.http import HttpRequest
creator = CreatorProfile.objects.first()
# 创建一个模拟的request对象
request = HttpRequest()
request.META['HTTP_HOST'] = 'localhost:8000'
request.META['wsgi.url_scheme'] = 'http'
serializer = CreatorProfileSerializer(creator, context={'request': request})
data = serializer.data
print("API响应示例:")
print(f"名称: {data['name']}")
print(f"本地头像字段: {data.get('avatar')}")
print(f"外部头像URL: {data.get('avatar_url')}")
print(f"实际显示URL: {data.get('avatar_display_url')}")
# 前端使用示例JavaScript
frontend_example = """
// 前端JavaScript使用示例
// 获取创作者数据
fetch('/api/daren_detail/creators/1/')
.then(response => response.json())
.then(data => {
// 显示头像
const avatarImg = document.getElementById('avatar');
// 使用avatar_display_url字段它会自动选择合适的URL
if (data.avatar_display_url) {
avatarImg.src = data.avatar_display_url;
avatarImg.style.display = 'block';
} else {
// 如果没有头像显示默认头像
avatarImg.src = '/static/images/default-avatar.png';
}
// 或者可以检查具体的字段类型
if (data.avatar) {
// 这是本地上传的图片
console.log('使用本地头像:', data.avatar);
} else if (data.avatar_url) {
// 这是外部URL
console.log('使用外部头像:', data.avatar_url);
}
});
// 上传头像示例
function uploadAvatar(file, creatorId) {
const formData = new FormData();
formData.append('avatar', file);
fetch(`/api/daren_detail/creators/${creatorId}/`, {
method: 'PATCH',
body: formData,
headers: {
'X-CSRFToken': getCookie('csrftoken') // CSRF令牌
}
})
.then(response => response.json())
.then(data => {
console.log('头像上传成功:', data.avatar_display_url);
// 更新页面上的头像显示
document.getElementById('avatar').src = data.avatar_display_url;
})
.catch(error => {
console.error('头像上传失败:', error);
});
}
"""
if __name__ == "__main__":
print("CreatorProfile头像字段使用示例")
print("="*50)
print()
print("1. 支持本地图片上传到 media/avatars/ 目录")
print("2. 支持外部URL链接")
print("3. get_avatar_url() 方法优先返回本地图片URL")
print("4. 序列化器提供avatar_display_url字段用于前端显示")
print()
print("前端JavaScript示例:")
print(frontend_example)