import json
|
|
from django.core.management.base import BaseCommand
|
|
from eventos.models import Noticia
|
|
from reymotausers.models import ReyMotaUser
|
|
|
|
|
|
class Command(BaseCommand):
|
|
help = "Importa noticias desde un archivo JSON"
|
|
|
|
def add_arguments(self, parser):
|
|
parser.add_argument('archivo_json', type=str, help="Ruta del archivo JSON")
|
|
|
|
def handle(self, *args, **kwargs):
|
|
archivo_json = kwargs['archivo_json']
|
|
|
|
try:
|
|
with open(archivo_json, 'r', encoding='utf-8') as file:
|
|
datos = json.load(file)
|
|
|
|
self.stdout.write(self.style.WARNING(f"\nSe encontraron {len(datos)} noticias en el archivo '{archivo_json}'."))
|
|
confirmar = input("¿Deseas continuar con la importación? (s/n): ").strip().lower()
|
|
|
|
if confirmar != 's':
|
|
self.stdout.write(self.style.ERROR("Importación cancelada."))
|
|
return
|
|
|
|
noticias_creados = 0
|
|
for noticia_data in datos:
|
|
try:
|
|
usuario = ReyMotaUser.objects.get(email=noticia_data["usuario_email"])
|
|
|
|
creado = Noticia.objects.create(
|
|
autor=usuario,
|
|
titulo=noticia_data['titulo'],
|
|
fecha_publicacion=noticia_data['fecha_publicacion'],
|
|
contenido=noticia_data['contenido'],
|
|
publicado=noticia_data['publicado']
|
|
)
|
|
if creado:
|
|
noticias_creados += 1
|
|
|
|
except ReyMotaUser.DoesNotExist:
|
|
self.stderr.write(self.style.ERROR(f"Usuario '{noticia_data['usuario']}' no encontrado."))
|
|
|
|
self.stdout.write(self.style.SUCCESS(f'Se importaron {noticias_creados} noticias correctamente.'))
|
|
|
|
except FileNotFoundError:
|
|
self.stderr.write(self.style.ERROR(f"El archivo {archivo_json} no se encontró."))
|
|
except json.JSONDecodeError:
|
|
self.stderr.write(self.style.ERROR("Error al leer el archivo JSON. Asegúrate de que el formato sea correcto."))
|