Django: Getting Started Transcripts
Chapter: Custom Django Commands
Lecture: Your first management command
Login or
purchase this course
to watch this video and the rest of the course contents.
0:00
I'm going to write a couple of commands inside of the catalog Django app. The first thing I have to do is create the necessary folder structure.
0:08
This is the parent as this is a Python module,
0:26
you need a dunder init file here, and then the folder where the commands go Also needs a dunder init.
0:50
Now that I've got the folders ready, I'll create a new file called authors.py.
1:11
To start off, I need to import base command, which my command class will inherit from. As I'm going to be playing with author data,
1:23
I need to import the author model class, and here I've defined a command. It can be named anything as long as inherits from base command.
1:40
I can optionally add a help attribute to the class and this will show up in the command line help info. Right out of the box,
1:47
you get a --help for your command without having to do much besides write this sentence. And this is the key part.
1:58
You need to override the base classes handle method. This is the entry point to your code, when your command is run.
2:06
Django will instansiate your object and call this method, passing in arguments and options from the command line. More on those later.
2:33
This is the beginning of the code for my command. This command is going to show information on the authors in the system.
2:41
I'm starting out by iterating over all the authors and creating some strings with author info
2:46
appending them to a list which I'm keeping in the variable named output.
3:01
Here, I'm adding more info if there's a picture or a message that says there isn't one if there is not.
3:11
And finally I just output this to the screen using standardout.write. Note that I haven't used print here. You can, but you shouldn't.
3:20
The base command provides hooks into the standard out and standard error streams.
3:25
It does this so that you can do funky things like control where they go. For example, when you go to test this,
3:31
you may want to ask the command to capture standard out for you. If you used print, you'd have to do this on your own.
3:38
If you stick with the streams provided by the base class, you'll have hooks into the streams. Let's go run our commands.