Customize Command in Django

Tram Ho

Django

Note

  • What you have been and will use Django would make no strangers statements as *** command python manage.py runserver, python manage.py createsuperuser … ***. So what is runserver, createsuperuser and how to create can create a custom command of their own.
  • By default in this section, you all have installed Django so I will not guide you again. Another small note is. If people here in the long term stick with open source then I think linux will be the ideal place for you ? .

1. Create Django project

2. Structure a Command

After creating the correct structure to create a custom command. Now you will declare the app to /custom_command/settings.py so Django will automatically receive new apps.

3. Command customization

The most interesting part is here. Now to perform the tasks you want to do when calling a command similar to Django does. You will create a file in the command directory. Here I have created a file named hello_world. To call the command hello_world, you use the command python manage.py hello_world . And here is the code in the file hello_world:

Test it and see what happens first everyone: python manage.py hello_world

4. Pass param in command

What if you wanted to pass param in the command? It is unbelievable that Django will support us all the way. Let’s see the following code to understand more

Passing param is simple, right? python manage.py hello_world Quang . You will get results

5. Summary

So you have to understand how to create a custom command in Django right. Do yourself a simple example as above to understand better. You can also expand it as to how to pass multiple params in the custom command. ?

Share the news now

Source : Viblo