This is the fifth day of my participation in Gwen Challenge

When writing Django projects, it is inevitable that we will use manage commands such as Django-admin startProject,python manage.py runserver… Wait for commands, and then those commands can do the corresponding thing.

Sometimes, however, Django doesn’t come with these commands, so you can write your own.

For example, we implement a createUser command. When we execute this command on the terminal, we create a User object in the database.

Preparation: First create a Django project, then create a new User app, and then write a user model in the User models file.

from django.db import models

# Create your models here.
class User(models.Model):
    name = models.CharField(max_length=20)
    telephone = models.CharField(max_length=11)
    email = models.EmailField()
Copy the code

In settings.py, I need to configure the database. Since I’m using mysql, I don’t need to configure it if I’m using Django’s default SQLite database.

Execute makemigRations and Migrate to map the model to the database.

At this point, we are ready to work.

Note: This app must be registered in settings.py. Otherwise, the customized command cannot be found

In Django, we want to write a custom manage command that follows Django’s rules for creating files.

Create a package named Management that must be identical to this package. Create a new package named Management and call it Commands. This creates the package that holds the manage command file, and then creates a new Python file with the name of the command. For example, I create a selfCommand file, which means the command I create is named selfCommand. The final directory structure of this app is:

With that, we have created the file to write the code.

To write the code, we create a class called Command, which must have this name. Then inherited from the django. Core. Management BaseCommand class.

from django.core.management import BaseCommand class Command(BaseCommand): Def handle(self, *args, **options): passCopy the code

The help variable can be written with or without the help variable. The function of this variable is the text displayed when using the -h or –help arguments of the command. Here we can write the function of this command, which is described.

Handle: This function is a mandatory function. When we use this command, the code in this function will be executed.

Since the main function of our command is to create a User user, we import the User object first and then start writing the code.

From user.models import user class Command(BaseCommand): help = 'create a user' def handle(self, *args, **options): Create (name='aaa',telephone=' 111111111111 ',email='[email protected]') self.stdout.write(' User created successfully ')Copy the code

Note: Instead of using print () to print information, we use self.stdout.write to print information.

Thus, we have written a simple command to create a User object. Then we execute the command at the terminal:

Python manage.py selfCommand (the name of the file at the bottom of the created package) 1 Then the terminal will print the information that the user has been created successfully, and then we can go to the database to view the information of the created user object

However, at this time, there will be an embarrassing problem, that is, when we create the user user, we certainly need others to input information, but we did not let others input information, but directly create a fixed user object. So, at this point, we need to add parameters to the command.

If we want to add arguments to the command, we need to create a new method in the class called add_argument.

Class Command(BaseCommand): help = 'create a user' def add_arguments(self, parser): Parser. add_argument('name',help=" specify the name field ") # name must be an argument. Mandatory parser.add_argument('-t','--telephone',help=" specify the telephone field ") # Optional arguments -t or --telephone -t are shorthand. def handle(self, *args, **options): name = options['name'] if options['telephone']: telephone = options['telephone'] else: telephone = '11111111111' User.objects.create(name=name,telephone=telephone,email='[email protected]') Self.stdout. write(' User created successfully ')Copy the code

We defined two parameters above, one mandatory and one optional, so we must pass the name parameter when using this command again, and the telephone parameter can not pass, then we in the Handel method to process the resulting parameters.

python manage.py selfcommand ccc

python manage.py selfcommand ddd -t 18888888888

We can also see the help for this command using Python manage.py -h and see our custom parameters.

When we use the command again, especially when we use some new commands, it is easy to use the command incorrectly, so we need to throw an exception to tell him that the command is used incorrectly.

First we import a class

from django.core.management import CommandError

For example, if we pass in a mobile phone number with more than 11 digits, we throw an exception:

def handle(self, *args, **options): name = options['name'] if options['telephone']: ['telephone'] if len(telephone) >= 11: Raise CommandError(" Mobile phone number cannot exceed 11 digits ") else: telephone = '11111111111' User.objects.create(name=name,telephone=telephone,email='[email protected]') Self.stdout. write(' User created successfully ')Copy the code

Here, we use the CommandError class to throw an exception, ensuring the robustness of our program.

When the user enters a phone number longer than 11 digits, an exception is thrown and the program terminates.

Note: The values we enter in the argument will be broken in the Handel function, even if we enter an integer. If we want to get an integer value, we can add type=int to add_argument().

Example:

Parser. Add_argument (‘id’,help=” id of user object “,type=int)

More about the custom of the manage orders operation can view the official document: docs.djangoproject.com/zh-hans/2.1…