https://github.com/arsho/django-custom-command
https://github.com/arsho/django-custom-command
Last synced: 2 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/arsho/django-custom-command
- Owner: arsho
- Created: 2020-03-30T17:46:08.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2021-09-22T18:49:17.000Z (almost 5 years ago)
- Last Synced: 2025-01-28T04:46:15.807Z (over 1 year ago)
- Language: Python
- Size: 198 KB
- Stars: 1
- Watchers: 2
- Forks: 1
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
## Django Custom Command Example with Django Docs Polls Application
This is the code repository of the following tutorial: [https://arshovon.com/blog/django-custom-command/](https://arshovon.com/blog/django-custom-command/)
### Directory Structure
```
.
├── mysite
│ ├── manage.py
│ ├── mysite
│ │ ├── asgi.py
│ │ ├── __init__.py
│ │ ├── settings.py
│ │ ├── urls.py
│ │ └── wsgi.py
│ └── polls
│ ├── admin.py
│ ├── apps.py
│ ├── __init__.py
│ ├── management
│ │ └── commands
│ │ ├── command_utils.py
│ │ ├── insert_dummy_questions.py
│ │ └── questions.csv
│ ├── migrations
│ │ ├── 0001_initial.py
│ │ └── __init__.py
│ ├── models.py
│ ├── templates
│ │ └── polls
│ │ ├── detail.html
│ │ ├── index.html
│ │ └── results.html
│ ├── tests.py
│ ├── urls.py
│ └── views.py
└── requirements.txt
```
### Installing Requirements
- Python version: 3.6+
- Create virtual environment:
```
python3 -m venv venv
```
- Activate virtual environment:
```
source venv/bin/activate
```
- Install required packages:
```
pip install -r requirements.txt
```
### Database Migration
- Create migration:
```
python manage.py makemigrations
```
- Migrate migrations:
```
python manage.py migrate
```
- Create super user:
```
python manage.py createsuperuser
```
### Run the project
- Run the project from the root directory of Django project:
```
python manage.py runserver
```
### Run Django Custom Command
- Run Django custom command `help` context:
```
python manage.py insert_dummy_questions --help
```

- Run Django custom command:
```
python manage.py insert_dummy_questions questions.csv
```

- After running Django custom command the CSV file data is inserted into database:

### Footnote
- I have used Django Docs Example Polls Application to demonstrate Django Custom Command.
- Utility methods of custom command files are kept in a separate file in `mysite/polls/management/commands/command_utils.py`. Then in custom command file I have imported required methods like: `from .command_utils import get_csv_file`
### Reference
- [Writing Django Custom Management Command](https://arshovon.com/blog/django-custom-command/)
- [Custom commands in Django](https://docs.djangoproject.com/en/2.2/howto/custom-management-commands/)
- [Writing your first Django app, part 1](https://docs.djangoproject.com/en/3.0/intro/tutorial01/)