How it works...

The principle of importing from an XLSX file is the same as with CSV. We open the file, read it row by row, form data dictionaries, validate them via a model form, and create the Song objects from the provided data.

Again, we are using the prepare(), main(), and finalize() methods to split the logic into more atomic parts.

Here is a detailed explanation of the main() method as it is probably the only different part of the management command:

  • Excel files are workbooks containing sheets as different tabs.
  • We are using the openpyxl library to open a file passed as a positional argument to the command. Then, we read the first sheet from the workbook.
  • The first row contains the column captions. We skip it.
  • Afterward, we will read the rows one by one as lists of values, use the zip() function to create dictionaries, pass them to a model form, validate, and create the Song objects from them.
  • If there are any validation errors and verbosity is greater than or equal to NORMAL, then we output the validation errors.
  • Once again, the management command will print out the imported songs to the console, unless you set --verbosity=0.

If we run the command twice with --verbosity=1 or higher, the output would be as follows:

You can learn more about how to work with Excel files at http://www.python-excel.org/.
..................Content has been hidden....................

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