Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating custom commands in django

Tags:

I have the following user model,

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(unique=True, max_length=255)
    mobile = PhoneNumberField(null=True)
    username = models.CharField(null=False, unique=True, max_length=255)
    full_name = models.CharField(max_length=255, blank=True, null=True)
    is_bot = models.BooleanField(default=False)

I want to create a custom command which could work like createsuperuser and creates a bot.

I have created a management package in the relevant app and added a command package inside that and a file createbot.py inside of that.

This is my code inside createbot.py

class Command(BaseCommand):
    def handle(self, email, username=None, password=None):
        user = User.objects.create(email,
                                   username=username,

                                   password=password,
                                   is_staff=True,
                                   is_superuser=True,
                                   is_active=True,
                                   is_bot=True
                                   )
        self.stdout.write(self.style.SUCCESS('Successfully create user bot with id: {}, email: {}'.format(user.id, user.email)))

I want this to work exactly like createsuper user giving me prompts to enter email, name and the works. But when I run it, I get the following,

TypeError: handle() got an unexpected keyword argument 'verbosity'

How can I get this to work?

like image 491
Melissa Stewart Avatar asked May 25 '18 21:05

Melissa Stewart


People also ask

What is Django admin commands?

django-admin is Django's command-line utility for administrative tasks. This document outlines all it can do. In addition, manage.py is automatically created in each Django project.

How use Django command-line?

Django can be installed easily using pip . In the command prompt, execute the following command: pip install django . This will download and install Django. After the installation has completed, you can verify your Django installation by executing django-admin --version in the command prompt.


1 Answers

Like is specified in the documentation on creating custom commands:

In addition to being able to add custom command line options, all management commands can accept some default options such as --verbosity and --traceback.

So that means the handle(..) function is invoked with those parameters, even if you are not interested in these.

You can however easily catch those and ignore them, by making using of keyword arguments:

class Command(BaseCommand):

    def handle(self, email, username=None, password=None, **other):
        # ...
        # perform actions
        pass

Here other is a dictionary that maps strings to values: the parameters with which the function is called, but that are not explicitly mentioned in the signature of the function.

The documentation also mentions how to specify the parameters you want to use in the handle, such that helptext can be generated when the user requests how to use the custom command. You can for example write:

class Command(BaseCommand):

    def add_arguments(self, parser):
        # Positional arguments
        parser.add_argument('email', required=True)

        # Named (optional) arguments
        parser.add_argument(
            '--username',
            help='The username for the user',
        )
        parser.add_argument(
            '--password',
            help='The password for the user',
        )

    def handle(self, email, username=None, password=None, **other):
        # ...
        # perform actions
        pass

Note that passwords are hashed in Django, hence you should use create_user(..).

like image 95
Willem Van Onsem Avatar answered Sep 28 '22 17:09

Willem Van Onsem