django-admin是Django的一个命令行管理工具,用以对Django项目执行某些命令操作。
1. django-admin安装
安装Django后,默认即安装了django-admin。
默认安装在$PATH_HOME/dist-packages/django/bin/django-admin.py
默认还在$PATH_HOME/Scripts/中安装了django-admin.exe和django-admin.py
2. 设置PATH路径加入django-admin所在位置
export PATH=$PATH;$PATH_HOME/dist-packages/django/bin/
后续就可以直接在Shell中执行
django-admin [options]
3. django-admin.py代码分析
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
5. django-admin命令的通用选项
6. 如果Django项目启用了django.contrib模块(默认启动),则django-admin还可以执行如下命令
1) django.contrib.auth的命令
2) django.contrib.contenttypes的命令
3) django.contrib.gis的命令
4) django.contrib.sessions的命令
5) django.contrib.sitemaps的命令
6) django.contrib.staticfiles的命令
7. 在项目代码中,也可以直接调用django-admin的命令
调用语句:
django.core.management.call_command(command_name, *args, **options)
示例:
from django.core import management
from django.core.management.commands import loaddata
management.call_command('flush', verbosity=0, interactive=False)
management.call_command('flush', '--verbosity=0', interactive=False)
management.call_command('loaddata', 'test_data', verbosity=0)
management.call_command(loaddata.Command(), 'test_data', verbosity=0)
事实上,在Django项目的代码中,manage.py文件的功能类似于django-admin,此外manage.py还:
manage.py源代码如下:
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mydjangolists.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv)
如果没有对Django进行任何设置,在执行django-admin命令时往往有警告,如下图所示:
而执行python3 manage.py则会自动应用所在项目的主模块中的settings.py,如下图所示:
因此建议使用python3 manage.py ...替代django-admin ...
事实上,如下命令是等价的:
django-admin
python3 manage.py
python3 -m django
参考链接:
https://docs.djangoproject.com/en/1.11/ref/django-admin/