Django 开发利器 django-extensions

2017-07-06

Django-extensions 可谓是 Django 开发利器。

安装

pip install django-extensions #其他方法 Google

配置

INSTALLED_APPS = (
    ...
    'django_extensions',
)

====================== 不是很完美的分割线 =====================

让 Django shell 更人性化

$ ./manage.py shell_plus --ipython #使用 ipython shell

$ ./manage.py shell_plus --bpython #使用 bpython shell

$ ./manage.py shell_plus --ptpython #使用 ptpython shell

$ ./manage.py shell_plus --plain  #当然也可以是纯 python, 不过这个是不是有点傻!!!

不过可以在 django settings.py 加入以下配置

SHELL_PLUS = "ptpython"

====================== 不是很完美的分割线 =====================

运行脚本更方便,不用在导入一大堆 django 配置了

  • 首先,在你的项目根目录下,创建 scrpit 文件夹
$ mkdir scripts
$ touch scripts/__init__.py
  • 接着,创建一个脚本文件
$ touch scripts/delete_all_questions.py
  • 再次,写脚本。注:代码必须写在 run() 函数下。
# scripts/delete_all_questions.py

from polls.models import Question

def run():
    # Fetch all questions
    questions = Question.objects.all()
    # Delete questions
    questions.delete()
  • 最后,运行脚本
$ python manage.py runscript delete_all_questions

$ python manage.py runscript delete_all_questions --traceback # 开启 Debug 模式

写在最后, 更多使用可以参考官方文档