777ca50328
update. 调整融合主菜单与板块 update. 分离新闻模块
85 lines
2.6 KiB
Python
85 lines
2.6 KiB
Python
import os
|
|
import random
|
|
import sys
|
|
import tempfile
|
|
|
|
import django
|
|
|
|
# 配置 Django 环境
|
|
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
|
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server.settings") # 修改为你的 settings 路径
|
|
django.setup()
|
|
|
|
# 2. 导入 Faker 和 模型
|
|
|
|
from faker import Faker
|
|
from article.models import Article, ArticleAttachment
|
|
from base.models import MainMenu
|
|
from users.models import User
|
|
from django.core.files import File # 引入 Django 的文件处理类
|
|
|
|
fake = Faker('zh_CN')
|
|
|
|
|
|
def seed_articles(count=20):
|
|
print(f"🚀 开始生成 {count} 篇文章...")
|
|
|
|
subsections = list(MainMenu.objects.filter(parent__isnull=False, visible=True))
|
|
users = list(User.objects.all())
|
|
|
|
if not subsections:
|
|
print("❌ 错误:数据库中没有找到任何子板块!")
|
|
return
|
|
|
|
if not users:
|
|
print("⚠️ 警告:数据库中没有用户,作者将设为空。")
|
|
|
|
created_count = 0
|
|
for i in range(count):
|
|
section = random.choice(subsections)
|
|
author = random.choice(users) if users else None
|
|
|
|
paragraphs = fake.paragraphs(nb=random.randint(3, 8))
|
|
content_html = "\n".join([f"<p>{p}</p>" for p in paragraphs])
|
|
|
|
article = Article.objects.create(
|
|
title=fake.sentence(nb_words=random.randint(5, 10))[:-1],
|
|
section=section,
|
|
author=author,
|
|
content=content_html,
|
|
is_published=True,
|
|
)
|
|
|
|
# --- 生成真实附件 ---
|
|
if random.random() < 0.3:
|
|
fake_filename = f"附件资料_{fake.word()}.pdf"
|
|
|
|
# 创建临时文件
|
|
with tempfile.NamedTemporaryFile(suffix='.pdf', delete=False) as tmp_file:
|
|
tmp_file.write(b'%PDF-1.4 Fake PDF Content for Testing')
|
|
tmp_file_path = tmp_file.name
|
|
|
|
try:
|
|
# 打开并保存
|
|
with open(tmp_file_path, 'rb') as f:
|
|
# 关键点:使用 file.save 方法,这会触发文件上传机制
|
|
attachment = ArticleAttachment(article=article)
|
|
attachment.file.save(fake_filename, File(f), save=True)
|
|
|
|
print(f" - [{section}] {article.title} (含真实附件)")
|
|
|
|
finally:
|
|
# 删除临时文件
|
|
if os.path.exists(tmp_file_path):
|
|
os.remove(tmp_file_path)
|
|
else:
|
|
print(f" - [{section}] {article.title}")
|
|
|
|
created_count += 1
|
|
|
|
print(f"✅ 成功生成 {created_count} 篇文章!")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
seed_articles(30)
|