| @ -0,0 +1,45 @@ | |||
| import json | |||
| from django.core.management.base import BaseCommand | |||
| from repostajes.models import Evento | |||
| class Command(BaseCommand): | |||
| help = "Importa eventos 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)} eventos 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 | |||
| eventos_creados = 0 | |||
| for evento_data in datos: | |||
| creado = Evento.objects.create( | |||
| id=evento_data['id'], | |||
| nombre=evento_data['nombre'], | |||
| descripcion=evento_data['descripcion'], | |||
| fecha=evento_data['fecha'], | |||
| plazas_disponibles=evento_data['plazas_disponibles'], | |||
| pubicado=evento_data['pubicado'], | |||
| url_imagen=evento_data['url_imagen'] | |||
| ) | |||
| if creado: | |||
| eventos_creados += 1 | |||
| self.stdout.write(self.style.SUCCESS(f'Se importaron {eventos_creados} eventos 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.")) | |||
| @ -0,0 +1,49 @@ | |||
| import json | |||
| from django.core.management.base import BaseCommand | |||
| from eventos.models import ListaEspera, Evento | |||
| from reymotausers.models import ReyMotaUser | |||
| class Command(BaseCommand): | |||
| help = "Importa listaesperas 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)} listaesperas 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 | |||
| listaesperas_creados = 0 | |||
| for listaespera_data in datos: | |||
| try: | |||
| evento = Evento.objects.get(id=listaespera_data["evento"]) | |||
| usuario = ReyMotaUser.objects.get(id=listaespera_data["usuario"]) | |||
| creado = ListaEspera.objects.create( | |||
| evento_id=evento.id, | |||
| usuario_id=usuario.id, | |||
| fecha_apuntado=listaespera_data['fecha_apuntado'], | |||
| ) | |||
| if creado: | |||
| listaesperas_creados += 1 | |||
| except Evento.DoesNotExist: | |||
| self.stderr.write(self.style.ERROR(f"Evento '{listaespera_data['evento']}' no encontrado.")) | |||
| self.stdout.write(self.style.SUCCESS(f'Se importaron {listaesperas_creados} listaesperas 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.")) | |||
| @ -0,0 +1,49 @@ | |||
| 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(id=noticia_data["usuario"]) | |||
| creado = Noticia.objects.create( | |||
| autor_id=usuario.id, | |||
| titulo=noticia_data['titulo'], | |||
| fecha_publicacion=noticia_data['fecha_publicacion'], | |||
| 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.")) | |||
| @ -0,0 +1,50 @@ | |||
| import json | |||
| from django.core.management.base import BaseCommand | |||
| from eventos.models import Reserva, Evento | |||
| from reymotausers.models import ReyMotaUser | |||
| class Command(BaseCommand): | |||
| help = "Importa reservas 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)} reservas 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 | |||
| reservas_creados = 0 | |||
| for reserva_data in datos: | |||
| try: | |||
| evento = Evento.objects.get(id=reserva_data["evento"]) | |||
| usuario = ReyMotaUser.objects.get(id=reserva_data["usuario"]) | |||
| creado = Reserva.objects.create( | |||
| evento_id=evento.id, | |||
| usuario_id=usuario.id, | |||
| fecha_reserva=reserva_data['fecha_reserva'], | |||
| evento=reserva_data['evento'] | |||
| ) | |||
| if creado: | |||
| reservas_creados += 1 | |||
| except Evento.DoesNotExist: | |||
| self.stderr.write(self.style.ERROR(f"Evento '{reserva_data['evento']}' no encontrado.")) | |||
| self.stdout.write(self.style.SUCCESS(f'Se importaron {reservas_creados} reservas 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.")) | |||
| @ -0,0 +1,26 @@ | |||
| from rest_framework import serializers | |||
| from .models import Evento, Reserva, ListaEspera, Noticia | |||
| class EventoSerializer(serializers.ModelSerializer): | |||
| class Meta: | |||
| model = Evento | |||
| fields = '__all__' # Incluir todos los campos del modelo | |||
| class ReservaSerializer(serializers.ModelSerializer): | |||
| class Meta: | |||
| model = Reserva | |||
| fields = '__all__' # Incluir todos los campos del modelo | |||
| class ListaEsperaSerializer(serializers.ModelSerializer): | |||
| class Meta: | |||
| model = ListaEspera | |||
| fields = '__all__' # Incluir todos los campos del modelo | |||
| class NoticiaSerializer(serializers.ModelSerializer): | |||
| class Meta: | |||
| model = Noticia | |||
| fields = '__all__' # Incluir todos los campos del modelo | |||
| @ -0,0 +1,48 @@ | |||
| import json | |||
| from django.core.management.base import BaseCommand | |||
| from reymotausers.models import ReyMotaUser | |||
| class Command(BaseCommand): | |||
| help = "Importa usuarios 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)} usuarios 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 | |||
| usuarios_creados = 0 | |||
| for usuario_data in datos: | |||
| creado = ReyMotaUser.objects.create( | |||
| foto=usuario_data['foto'], | |||
| password=usuario_data['password'], | |||
| is_superuser=usuario_data['is_superuser'], | |||
| is_staff=usuario_data['is_staff'], | |||
| is_active=usuario_data['is_active'], | |||
| nombre=usuario_data['nombre'], | |||
| email=usuario_data['email'], | |||
| groups=usuario_data['groups'], | |||
| user_permissions=usuario_data['user_permissions'], | |||
| last_login=usuario_data['last_login'] | |||
| ) | |||
| if creado: | |||
| usuarios_creados += 1 | |||
| self.stdout.write(self.style.SUCCESS(f'Se importaron {usuarios_creados} usuarios 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.")) | |||
| @ -0,0 +1,8 @@ | |||
| from rest_framework import serializers | |||
| from .models import ReyMotaUser | |||
| class ReyMotaUserSerializer(serializers.ModelSerializer): | |||
| class Meta: | |||
| model = ReyMotaUser | |||
| fields = '__all__' # Incluir todos los campos del modelo | |||
| @ -0,0 +1,9 @@ | |||
| from django.urls import path | |||
| from . import views | |||
| from .views import api_lista_usuarios, api_detalle_usuario | |||
| urlpatterns = [ | |||
| path('api/usuarios/', api_lista_usuarios, name='api_lista_usuarios'), | |||
| path('api/usuarios/<int:usuario_id>/', api_detalle_usuario, name='api_detalle_usuario'), | |||
| ] | |||
| @ -1,3 +1,29 @@ | |||
| from django.shortcuts import render | |||
| from rest_framework.response import Response | |||
| from rest_framework.decorators import api_view | |||
| from .serializers import ReyMotaUserSerializer | |||
| from .models import ReyMotaUser | |||
| # Create your views here. | |||
| @api_view(['GET']) | |||
| def api_lista_usuarios(request): | |||
| """Devuelve la lista de todos los usuarios.""" | |||
| usuarios = ReyMotaUser.objects.all() | |||
| serializer = ReyMotaUserSerializer(usuarios, many=True) | |||
| return Response(serializer.data) | |||
| @api_view(['GET']) | |||
| def api_detalle_usuario(request, usuario_id): | |||
| """Devuelve los detalles de un usuario específico.""" | |||
| try: | |||
| usuario = ReyMotaUser.objects.get(id=usuario_id) | |||
| serializer = ReyMotaUserSerializer(usuario) | |||
| return Response(serializer.data) | |||
| except ReyMotaUser.DoesNotExist: | |||
| return Response({'error': 'Canción no encontrada'}, status=404) | |||