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
1 2 3 4 5 6 7 8 9 | # Câu lệnh khởi tạo một project Django django-admin startproject custom_command # Di chuyển vào trong project cd custom_command # Tạo một app django-admin startapp polls |
2. Structure a Command
1 2 3 4 5 6 7 8 9 10 11 12 13 | # Tạo package management và command trong polls có cấu trúc như sau polls/ __init__.py models.py management/ __init__.py commands/ __init__.py _private.py hello_world.py tests.py views.py |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # My App 'polls', ) |
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:
1 2 3 4 5 6 7 8 9 10 11 12 | <span class="token keyword">from</span> django <span class="token punctuation">.</span> core <span class="token punctuation">.</span> management <span class="token punctuation">.</span> base <span class="token keyword">import</span> BaseCommand <span class="token keyword">class</span> <span class="token class-name">Command</span> <span class="token punctuation">(</span> BaseCommand <span class="token punctuation">)</span> <span class="token punctuation">:</span> <span class="token keyword">def</span> <span class="token function">handle</span> <span class="token punctuation">(</span> self <span class="token punctuation">,</span> <span class="token operator">*</span> args <span class="token punctuation">,</span> <span class="token operator">**</span> options <span class="token punctuation">)</span> <span class="token punctuation">:</span> self <span class="token punctuation">.</span> stdout <span class="token punctuation">.</span> write <span class="token punctuation">(</span> <span class="token string">'[#] Begin execute...'</span> <span class="token punctuation">)</span> <span class="token keyword">try</span> <span class="token punctuation">:</span> self <span class="token punctuation">.</span> stdout <span class="token punctuation">.</span> write <span class="token punctuation">(</span> <span class="token string">'[#] Hello World!'</span> <span class="token punctuation">)</span> <span class="token keyword">except</span> Exception <span class="token keyword">as</span> e <span class="token punctuation">:</span> <span class="token keyword">print</span> <span class="token punctuation">(</span> <span class="token string">'Error:'</span> <span class="token punctuation">,</span> e <span class="token punctuation">)</span> self <span class="token punctuation">.</span> stdout <span class="token punctuation">.</span> write <span class="token punctuation">(</span> <span class="token string">'[#] DONE!'</span> <span class="token punctuation">)</span> |
Test it and see what happens first everyone: python manage.py hello_world
1 2 3 4 | [#] Begin execute... [#] Hello World! [#] DONE! |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('params1', nargs='?', type=str) def handle(self, *args, **options): # Using parameters: param1 = options['params1'] self.stdout.write('[#] Begin execute...') try: if param1: self.stdout.write('[#] Hello ' + str(param1)) else: self.stdout.write('[#] Hello World') except Exception as e: print('Error:', e) self.stdout.write('[#] DONE!') |
Passing param is simple, right? python manage.py hello_world Quang . You will get results
1 2 3 4 | [#] Begin execute... [#] Hello Quang [#] DONE! |
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.