from pathlib import Path from django.core.management.base import BaseCommand, CommandError import argparse from oef.models import Entry from bs4 import BeautifulSoup class Command(BaseCommand): help = "Imports the RCR spreadsheet" def add_arguments(self, parser): # parser.add_argument("poll_ids", nargs="+", type=int) parser.add_argument('--file', type=argparse.FileType('r')) def handle(self, *args, **options): #with open(options["file"]) as f: soup = BeautifulSoup(options["file"], "html.parser") Entry.objects.all().delete() rows = 0 for row in soup.find_all("tr"): if rows > 0: entry.questions = entry.questions + "\n" + row.find_all("td")[0].text rows = rows - 1 if rows == 0: entry.questions_original = entry.questions entry.save() continue cells = row.find_all("td") if cells[0].text == "Modality": continue entry = Entry() entry.modality = cells[0].text entry.exam_code = cells[1].text entry.exam_name = cells[2].text entry.questions = cells[3].text entry.oef_name = cells[4].text entry.comments = cells[5].text if cells[0].has_attr("rowspan"): rows = int(cells[0]["rowspan"]) - 1 else: entry.questions_original = entry.questions entry.save() #Entry.objects.all().delete() #for row in soup.find_all("tr"): # cells = row.find_all("td") # if len(cells) == 6: # entry = Entry() # entry.modality = cells[0].text # entry.exam_code = cells[1].text # entry.exam_name = cells[2].text # entry.questions = cells[3].text # #entry. # entry.comments = cells[5].text # entry.save() # self.stdout.write( # self.style.SUCCESS(f"Entry added: {entry.pk}/{entry.exam_name}") # ) # else: # self.stdout.write( # self.style.WARNING(f"Skipping row: {row}") # )