How to do it...

Follow these steps to create and use a management command that imports songs from a local XLSX file:

  1. Create an XLSX file with the column names Artist, Title, and URL in the first row. Add some song data to it in the next rows matching the columns. You can do this in a spreadsheet application, by saving the CSV file from the previous recipe as an XLSX file, data/music.xlsx. Here is an example:

  1. If you haven't done so, in the music app, create a management directory and then a commands subdirectory beneath it. Add empty __init__.py files in both of the new directories to make them Python packages.
  2. Add an import_music_from_xlsx.py file with the following content:
# myproject/apps/music/management/commands
# /import_music_from_xlsx.py

from
django.core.management.base import BaseCommand

class Command(BaseCommand):
help = (
"Imports music from a local XLSX file. "
"Expects columns: Artist, Title, URL"
)
SILENT, NORMAL, VERBOSE, VERY_VERBOSE = 0, 1, 2, 3

def add_arguments(self, parser):
# Positional arguments
parser.add_argument("file_path",
nargs=1,
type=str)

def handle(self, *args, **options):
self.verbosity = options.get("verbosity", self.NORMAL)
self.file_path = options["file_path"][0]
self.prepare()
self.main()
self.finalize()
  1. Then, in the same file for the Command class, create a prepare() method:
    def prepare(self):
self.imported_counter = 0
self.skipped_counter = 0
  1. Then, create the main() method there:
    def main(self):
from openpyxl import load_workbook
from ...forms import SongForm

wb = load_workbook(filename=self.file_path)
ws = wb.worksheets[0]

if self.verbosity >= self.NORMAL:
self.stdout.write("=== Importing music ===")

columns = ["artist", "title", "url"]
rows = ws.iter_rows(min_row=2) # skip the column captions
for index, row in enumerate(rows, start=1):
row_values = [cell.value for cell in row]
row_dict = dict(zip(columns, row_values))
form = SongForm(data=row_dict)
if form.is_valid():
song = form.save()
if self.verbosity >= self.NORMAL:
self.stdout.write(f" - {song} ")
self.imported_counter += 1
else:
if self.verbosity >= self.NORMAL:
self.stderr.write(
f"Errors importing song "
f"{row_dict['artist']} -
{row_dict['title']}: "
)
self.stderr.write(f"{form.errors.as_json()} ")
self.skipped_counter += 1
  1. And we'll finish the class with the finalize() method:
    def finalize(self):
if self.verbosity >= self.NORMAL:
self.stdout.write(f"------------------------- ")
self.stdout.write(f"Songs imported:
{self.imported_counter} ")
self.stdout.write(f"Songs skipped:
{self.skipped_counter} ")
  1. To run the import, call the following in the command line:
(env)$ python manage.py import_music_from_xlsx data/music.xlsx
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.86.155