django-admin.txt 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854
  1. ==================================
  2. ``django-admin`` and ``manage.py``
  3. ==================================
  4. ``django-admin`` is Django's command-line utility for administrative tasks.
  5. This document outlines all it can do.
  6. In addition, ``manage.py`` is automatically created in each Django project.
  7. ``manage.py`` does the same thing as ``django-admin`` but takes care of a few
  8. things for you:
  9. * It puts your project's package on ``sys.path``.
  10. * It sets the :envvar:`DJANGO_SETTINGS_MODULE` environment variable so that
  11. it points to your project's ``settings.py`` file.
  12. The ``django-admin`` script should be on your system path if you installed
  13. Django via its ``setup.py`` utility. If it's not on your path, you can find it
  14. in ``site-packages/django/bin`` within your Python installation. Consider
  15. symlinking it from some place on your path, such as ``/usr/local/bin``.
  16. For Windows users, who do not have symlinking functionality available, you can
  17. copy ``django-admin.exe`` to a location on your existing path or edit the
  18. ``PATH`` settings (under ``Settings - Control Panel - System - Advanced -
  19. Environment...``) to point to its installed location.
  20. Generally, when working on a single Django project, it's easier to use
  21. ``manage.py`` than ``django-admin``. If you need to switch between multiple
  22. Django settings files, use ``django-admin`` with
  23. :envvar:`DJANGO_SETTINGS_MODULE` or the :option:`--settings` command line
  24. option.
  25. The command-line examples throughout this document use ``django-admin`` to
  26. be consistent, but any example can use ``manage.py`` or ``python -m django``
  27. just as well.
  28. Usage
  29. =====
  30. .. console::
  31. $ django-admin <command> [options]
  32. $ manage.py <command> [options]
  33. $ python -m django <command> [options]
  34. ``command`` should be one of the commands listed in this document.
  35. ``options``, which is optional, should be zero or more of the options available
  36. for the given command.
  37. Getting runtime help
  38. --------------------
  39. .. django-admin:: help
  40. Run ``django-admin help`` to display usage information and a list of the
  41. commands provided by each application.
  42. Run ``django-admin help --commands`` to display a list of all available
  43. commands.
  44. Run ``django-admin help <command>`` to display a description of the given
  45. command and a list of its available options.
  46. App names
  47. ---------
  48. Many commands take a list of "app names." An "app name" is the basename of
  49. the package containing your models. For example, if your :setting:`INSTALLED_APPS`
  50. contains the string ``'mysite.blog'``, the app name is ``blog``.
  51. Determining the version
  52. -----------------------
  53. .. django-admin:: version
  54. Run ``django-admin version`` to display the current Django version.
  55. The output follows the schema described in :pep:`440`::
  56. 1.4.dev17026
  57. 1.4a1
  58. 1.4
  59. Displaying debug output
  60. -----------------------
  61. .. program:: None
  62. Use :option:`--verbosity` to specify the amount of notification and debug
  63. information that ``django-admin`` prints to the console.
  64. Available commands
  65. ==================
  66. ``check``
  67. ---------
  68. .. django-admin:: check [app_label [app_label ...]]
  69. Uses the :doc:`system check framework </ref/checks>` to inspect the entire
  70. Django project for common problems.
  71. By default, all apps will be checked. You can check a subset of apps by
  72. providing a list of app labels as arguments::
  73. django-admin check auth admin myapp
  74. If you do not specify any app, all apps will be checked.
  75. .. django-admin-option:: --tag TAGS, -t TAGS
  76. The system check framework performs many different types of checks that are
  77. :ref:`categorized with tags <system-check-builtin-tags>`. You can use these
  78. tags to restrict the checks performed to just those in a particular category.
  79. For example, to perform only models and compatibility checks, run::
  80. django-admin check --tag models --tag compatibility
  81. .. django-admin-option:: --list-tags
  82. Lists all available tags.
  83. .. django-admin-option:: --deploy
  84. Activates some additional checks that are only relevant in a deployment setting.
  85. You can use this option in your local development environment, but since your
  86. local development settings module may not have many of your production settings,
  87. you will probably want to point the ``check`` command at a different settings
  88. module, either by setting the ``DJANGO_SETTINGS_MODULE`` environment variable,
  89. or by passing the ``--settings`` option::
  90. django-admin check --deploy --settings=production_settings
  91. Or you could run it directly on a production or staging deployment to verify
  92. that the correct settings are in use (omitting ``--settings``). You could even
  93. make it part of your integration test suite.
  94. .. django-admin-option:: --fail-level {CRITICAL,ERROR,WARNING,INFO,DEBUG}
  95. Specifies the message level that will cause the command to exit with a non-zero
  96. status. Default is ``ERROR``.
  97. ``compilemessages``
  98. -------------------
  99. .. django-admin:: compilemessages
  100. Compiles ``.po`` files created by :djadmin:`makemessages` to ``.mo`` files for
  101. use with the built-in gettext support. See :doc:`/topics/i18n/index`.
  102. .. django-admin-option:: --locale LOCALE, -l LOCALE
  103. Specifies the locale(s) to process. If not provided, all locales are processed.
  104. .. django-admin-option:: --exclude EXCLUDE, -x EXCLUDE
  105. Specifies the locale(s) to exclude from processing. If not provided, no locales
  106. are excluded.
  107. .. django-admin-option:: --use-fuzzy, -f
  108. Includes fuzzy translations into compiled files.
  109. Example usage::
  110. django-admin compilemessages --locale=pt_BR
  111. django-admin compilemessages --locale=pt_BR --locale=fr -f
  112. django-admin compilemessages -l pt_BR
  113. django-admin compilemessages -l pt_BR -l fr --use-fuzzy
  114. django-admin compilemessages --exclude=pt_BR
  115. django-admin compilemessages --exclude=pt_BR --exclude=fr
  116. django-admin compilemessages -x pt_BR
  117. django-admin compilemessages -x pt_BR -x fr
  118. ``createcachetable``
  119. --------------------
  120. .. django-admin:: createcachetable
  121. Creates the cache tables for use with the database cache backend using the
  122. information from your settings file. See :doc:`/topics/cache` for more
  123. information.
  124. .. django-admin-option:: --database DATABASE
  125. Specifies the database in which the cache table(s) will be created. Defaults to
  126. ``default``.
  127. .. django-admin-option:: --dry-run
  128. Prints the SQL that would be run without actually running it, so you can
  129. customize it or use the migrations framework.
  130. ``dbshell``
  131. -----------
  132. .. django-admin:: dbshell
  133. Runs the command-line client for the database engine specified in your
  134. :setting:`ENGINE <DATABASE-ENGINE>` setting, with the connection parameters
  135. specified in your :setting:`USER`, :setting:`PASSWORD`, etc., settings.
  136. * For PostgreSQL, this runs the ``psql`` command-line client.
  137. * For MySQL, this runs the ``mysql`` command-line client.
  138. * For SQLite, this runs the ``sqlite3`` command-line client.
  139. * For Oracle, this runs the ``sqlplus`` command-line client.
  140. This command assumes the programs are on your ``PATH`` so that a simple call to
  141. the program name (``psql``, ``mysql``, ``sqlite3``, ``sqlplus``) will find the
  142. program in the right place. There's no way to specify the location of the
  143. program manually.
  144. .. django-admin-option:: --database DATABASE
  145. Specifies the database onto which to open a shell. Defaults to ``default``.
  146. ``diffsettings``
  147. ----------------
  148. .. django-admin:: diffsettings
  149. Displays differences between the current settings file and Django's default
  150. settings (or another settings file specified by :option:`--default`).
  151. Settings that don't appear in the defaults are followed by ``"###"``. For
  152. example, the default settings don't define :setting:`ROOT_URLCONF`, so
  153. :setting:`ROOT_URLCONF` is followed by ``"###"`` in the output of
  154. ``diffsettings``.
  155. .. django-admin-option:: --all
  156. Displays all settings, even if they have Django's default value. Such settings
  157. are prefixed by ``"###"``.
  158. .. django-admin-option:: --default MODULE
  159. The settings module to compare the current settings against. Leave empty to
  160. compare against Django's default settings.
  161. .. django-admin-option:: --output {hash,unified}
  162. .. versionadded:: 2.0
  163. Specifies the output format. Available values are ``hash`` and ``unified``.
  164. ``hash`` is the default mode that displays the output that's described above.
  165. ``unified`` displays the output similar to ``diff -u``. Default settings are
  166. prefixed with a minus sign, followed by the changed setting prefixed with a
  167. plus sign.
  168. ``dumpdata``
  169. ------------
  170. .. django-admin:: dumpdata [app_label[.ModelName] [app_label[.ModelName] ...]]
  171. Outputs to standard output all data in the database associated with the named
  172. application(s).
  173. If no application name is provided, all installed applications will be dumped.
  174. The output of ``dumpdata`` can be used as input for :djadmin:`loaddata`.
  175. Note that ``dumpdata`` uses the default manager on the model for selecting the
  176. records to dump. If you're using a :ref:`custom manager <custom-managers>` as
  177. the default manager and it filters some of the available records, not all of the
  178. objects will be dumped.
  179. .. django-admin-option:: --all, -a
  180. Uses Django's base manager, dumping records which might otherwise be filtered
  181. or modified by a custom manager.
  182. .. django-admin-option:: --format FORMAT
  183. Specifies the serialization format of the output. Defaults to JSON. Supported
  184. formats are listed in :ref:`serialization-formats`.
  185. .. django-admin-option:: --indent INDENT
  186. Specifies the number of indentation spaces to use in the output. Defaults to
  187. ``None`` which displays all data on single line.
  188. .. django-admin-option:: --exclude EXCLUDE, -e EXCLUDE
  189. Prevents specific applications or models (specified in the form of
  190. ``app_label.ModelName``) from being dumped. If you specify a model name, the
  191. output will be restricted to that model, rather than the entire application.
  192. You can also mix application names and model names.
  193. If you want to exclude multiple applications, pass ``--exclude`` more than
  194. once::
  195. django-admin dumpdata --exclude=auth --exclude=contenttypes
  196. .. django-admin-option:: --database DATABASE
  197. Specifies the database from which data will be dumped. Defaults to ``default``.
  198. .. django-admin-option:: --natural-foreign
  199. Uses the ``natural_key()`` model method to serialize any foreign key and
  200. many-to-many relationship to objects of the type that defines the method. If
  201. you're dumping ``contrib.auth`` ``Permission`` objects or
  202. ``contrib.contenttypes`` ``ContentType`` objects, you should probably use this
  203. flag. See the :ref:`natural keys <topics-serialization-natural-keys>`
  204. documentation for more details on this and the next option.
  205. .. django-admin-option:: --natural-primary
  206. Omits the primary key in the serialized data of this object since it can be
  207. calculated during deserialization.
  208. .. django-admin-option:: --pks PRIMARY_KEYS
  209. Outputs only the objects specified by a comma separated list of primary keys.
  210. This is only available when dumping one model. By default, all the records of
  211. the model are output.
  212. .. django-admin-option:: --output OUTPUT, -o OUTPUT
  213. Specifies a file to write the serialized data to. By default, the data goes to
  214. standard output.
  215. When this option is set and ``--verbosity`` is greater than 0 (the default), a
  216. progress bar is shown in the terminal.
  217. ``flush``
  218. ---------
  219. .. django-admin:: flush
  220. Removes all data from the database and re-executes any post-synchronization
  221. handlers. The table of which migrations have been applied is not cleared.
  222. If you would rather start from an empty database and re-run all migrations, you
  223. should drop and recreate the database and then run :djadmin:`migrate` instead.
  224. .. django-admin-option:: --noinput, --no-input
  225. Suppresses all user prompts.
  226. .. django-admin-option:: --database DATABASE
  227. Specifies the database to flush. Defaults to ``default``.
  228. ``inspectdb``
  229. -------------
  230. .. django-admin:: inspectdb [table [table ...]]
  231. Introspects the database tables in the database pointed-to by the
  232. :setting:`NAME` setting and outputs a Django model module (a ``models.py``
  233. file) to standard output.
  234. You may choose what tables or views to inspect by passing their names as
  235. arguments. If no arguments are provided, models are created for views only if
  236. the :option:`--include-views` option is used.
  237. Use this if you have a legacy database with which you'd like to use Django.
  238. The script will inspect the database and create a model for each table within
  239. it.
  240. As you might expect, the created models will have an attribute for every field
  241. in the table. Note that ``inspectdb`` has a few special cases in its field-name
  242. output:
  243. * If ``inspectdb`` cannot map a column's type to a model field type, it'll
  244. use ``TextField`` and will insert the Python comment
  245. ``'This field type is a guess.'`` next to the field in the generated
  246. model. The recognized fields may depend on apps listed in
  247. :setting:`INSTALLED_APPS`. For example, :mod:`django.contrib.postgres` adds
  248. recognition for several PostgreSQL-specific field types.
  249. * If the database column name is a Python reserved word (such as
  250. ``'pass'``, ``'class'`` or ``'for'``), ``inspectdb`` will append
  251. ``'_field'`` to the attribute name. For example, if a table has a column
  252. ``'for'``, the generated model will have a field ``'for_field'``, with
  253. the ``db_column`` attribute set to ``'for'``. ``inspectdb`` will insert
  254. the Python comment
  255. ``'Field renamed because it was a Python reserved word.'`` next to the
  256. field.
  257. This feature is meant as a shortcut, not as definitive model generation. After
  258. you run it, you'll want to look over the generated models yourself to make
  259. customizations. In particular, you'll need to rearrange models' order, so that
  260. models that refer to other models are ordered properly.
  261. Primary keys are automatically introspected for PostgreSQL, MySQL and
  262. SQLite, in which case Django puts in the ``primary_key=True`` where
  263. needed.
  264. ``inspectdb`` works with PostgreSQL, MySQL and SQLite. Foreign-key detection
  265. only works in PostgreSQL and with certain types of MySQL tables.
  266. Django doesn't create database defaults when a
  267. :attr:`~django.db.models.Field.default` is specified on a model field.
  268. Similarly, database defaults aren't translated to model field defaults or
  269. detected in any fashion by ``inspectdb``.
  270. By default, ``inspectdb`` creates unmanaged models. That is, ``managed = False``
  271. in the model's ``Meta`` class tells Django not to manage each table's creation,
  272. modification, and deletion. If you do want to allow Django to manage the
  273. table's lifecycle, you'll need to change the
  274. :attr:`~django.db.models.Options.managed` option to ``True`` (or simply remove
  275. it because ``True`` is its default value).
  276. .. django-admin-option:: --database DATABASE
  277. Specifies the database to introspect. Defaults to ``default``.
  278. .. django-admin-option:: --include-views
  279. .. versionadded:: 2.1
  280. If this option is provided, models are also created for database views.
  281. ``loaddata``
  282. ------------
  283. .. django-admin:: loaddata fixture [fixture ...]
  284. Searches for and loads the contents of the named fixture into the database.
  285. .. django-admin-option:: --database DATABASE
  286. Specifies the database into which the data will be loaded. Defaults to
  287. ``default``.
  288. .. django-admin-option:: --ignorenonexistent, -i
  289. Ignores fields and models that may have been removed since the fixture was
  290. originally generated.
  291. .. django-admin-option:: --app APP_LABEL
  292. Specifies a single app to look for fixtures in rather than looking in all apps.
  293. .. django-admin-option:: --format FORMAT
  294. .. versionadded:: 2.0
  295. Specifies the :ref:`serialization format <serialization-formats>` (e.g.,
  296. ``json`` or ``xml``) for fixtures :ref:`read from stdin
  297. <loading-fixtures-stdin>`.
  298. .. django-admin-option:: --exclude EXCLUDE, -e EXCLUDE
  299. Excludes loading the fixtures from the given applications and/or models (in the
  300. form of ``app_label`` or ``app_label.ModelName``). Use the option multiple
  301. times to exclude more than one app or model.
  302. What's a "fixture"?
  303. ~~~~~~~~~~~~~~~~~~~
  304. A *fixture* is a collection of files that contain the serialized contents of
  305. the database. Each fixture has a unique name, and the files that comprise the
  306. fixture can be distributed over multiple directories, in multiple applications.
  307. Django will search in three locations for fixtures:
  308. 1. In the ``fixtures`` directory of every installed application
  309. 2. In any directory named in the :setting:`FIXTURE_DIRS` setting
  310. 3. In the literal path named by the fixture
  311. Django will load any and all fixtures it finds in these locations that match
  312. the provided fixture names.
  313. If the named fixture has a file extension, only fixtures of that type
  314. will be loaded. For example::
  315. django-admin loaddata mydata.json
  316. would only load JSON fixtures called ``mydata``. The fixture extension
  317. must correspond to the registered name of a
  318. :ref:`serializer <serialization-formats>` (e.g., ``json`` or ``xml``).
  319. If you omit the extensions, Django will search all available fixture types
  320. for a matching fixture. For example::
  321. django-admin loaddata mydata
  322. would look for any fixture of any fixture type called ``mydata``. If a fixture
  323. directory contained ``mydata.json``, that fixture would be loaded
  324. as a JSON fixture.
  325. The fixtures that are named can include directory components. These
  326. directories will be included in the search path. For example::
  327. django-admin loaddata foo/bar/mydata.json
  328. would search ``<app_label>/fixtures/foo/bar/mydata.json`` for each installed
  329. application, ``<dirname>/foo/bar/mydata.json`` for each directory in
  330. :setting:`FIXTURE_DIRS`, and the literal path ``foo/bar/mydata.json``.
  331. When fixture files are processed, the data is saved to the database as is.
  332. Model defined :meth:`~django.db.models.Model.save` methods are not called, and
  333. any :data:`~django.db.models.signals.pre_save` or
  334. :data:`~django.db.models.signals.post_save` signals will be called with
  335. ``raw=True`` since the instance only contains attributes that are local to the
  336. model. You may, for example, want to disable handlers that access
  337. related fields that aren't present during fixture loading and would otherwise
  338. raise an exception::
  339. from django.db.models.signals import post_save
  340. from .models import MyModel
  341. def my_handler(**kwargs):
  342. # disable the handler during fixture loading
  343. if kwargs['raw']:
  344. return
  345. ...
  346. post_save.connect(my_handler, sender=MyModel)
  347. You could also write a simple decorator to encapsulate this logic::
  348. from functools import wraps
  349. def disable_for_loaddata(signal_handler):
  350. """
  351. Decorator that turns off signal handlers when loading fixture data.
  352. """
  353. @wraps(signal_handler)
  354. def wrapper(*args, **kwargs):
  355. if kwargs['raw']:
  356. return
  357. signal_handler(*args, **kwargs)
  358. return wrapper
  359. @disable_for_loaddata
  360. def my_handler(**kwargs):
  361. ...
  362. Just be aware that this logic will disable the signals whenever fixtures are
  363. deserialized, not just during ``loaddata``.
  364. Note that the order in which fixture files are processed is undefined. However,
  365. all fixture data is installed as a single transaction, so data in
  366. one fixture can reference data in another fixture. If the database backend
  367. supports row-level constraints, these constraints will be checked at the
  368. end of the transaction.
  369. The :djadmin:`dumpdata` command can be used to generate input for ``loaddata``.
  370. Compressed fixtures
  371. ~~~~~~~~~~~~~~~~~~~
  372. Fixtures may be compressed in ``zip``, ``gz``, or ``bz2`` format. For example::
  373. django-admin loaddata mydata.json
  374. would look for any of ``mydata.json``, ``mydata.json.zip``,
  375. ``mydata.json.gz``, or ``mydata.json.bz2``. The first file contained within a
  376. zip-compressed archive is used.
  377. Note that if two fixtures with the same name but different
  378. fixture type are discovered (for example, if ``mydata.json`` and
  379. ``mydata.xml.gz`` were found in the same fixture directory), fixture
  380. installation will be aborted, and any data installed in the call to
  381. ``loaddata`` will be removed from the database.
  382. .. admonition:: MySQL with MyISAM and fixtures
  383. The MyISAM storage engine of MySQL doesn't support transactions or
  384. constraints, so if you use MyISAM, you won't get validation of fixture
  385. data, or a rollback if multiple transaction files are found.
  386. Database-specific fixtures
  387. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  388. If you're in a multi-database setup, you might have fixture data that
  389. you want to load onto one database, but not onto another. In this
  390. situation, you can add a database identifier into the names of your fixtures.
  391. For example, if your :setting:`DATABASES` setting has a 'master' database
  392. defined, name the fixture ``mydata.master.json`` or
  393. ``mydata.master.json.gz`` and the fixture will only be loaded when you
  394. specify you want to load data into the ``master`` database.
  395. .. _loading-fixtures-stdin:
  396. Loading fixtures from ``stdin``
  397. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  398. .. versionadded:: 2.0
  399. You can use a dash as the fixture name to load input from ``sys.stdin``. For
  400. example::
  401. django-admin loaddata --format=json -
  402. When reading from ``stdin``, the :option:`--format <loaddata --format>` option
  403. is required to specify the :ref:`serialization format <serialization-formats>`
  404. of the input (e.g., ``json`` or ``xml``).
  405. Loading from ``stdin`` is useful with standard input and output redirections.
  406. For example::
  407. django-admin dumpdata --format=json --database=test app_label.ModelName | django-admin loaddata --format=json --database=prod -
  408. ``makemessages``
  409. ----------------
  410. .. django-admin:: makemessages
  411. Runs over the entire source tree of the current directory and pulls out all
  412. strings marked for translation. It creates (or updates) a message file in the
  413. conf/locale (in the Django tree) or locale (for project and application)
  414. directory. After making changes to the messages files you need to compile them
  415. with :djadmin:`compilemessages` for use with the builtin gettext support. See
  416. the :ref:`i18n documentation <how-to-create-language-files>` for details.
  417. This command doesn't require configured settings. However, when settings aren't
  418. configured, the command can't ignore the :setting:`MEDIA_ROOT` and
  419. :setting:`STATIC_ROOT` directories or include :setting:`LOCALE_PATHS`. It will
  420. also write files in UTF-8 rather than in :setting:`FILE_CHARSET`.
  421. .. django-admin-option:: --all, -a
  422. Updates the message files for all available languages.
  423. .. django-admin-option:: --extension EXTENSIONS, -e EXTENSIONS
  424. Specifies a list of file extensions to examine (default: ``html``, ``txt``,
  425. ``py`` or ``js`` if :option:`--domain` is ``js``).
  426. Example usage::
  427. django-admin makemessages --locale=de --extension xhtml
  428. Separate multiple extensions with commas or use ``-e`` or ``--extension``
  429. multiple times::
  430. django-admin makemessages --locale=de --extension=html,txt --extension xml
  431. .. django-admin-option:: --locale LOCALE, -l LOCALE
  432. Specifies the locale(s) to process.
  433. .. django-admin-option:: --exclude EXCLUDE, -x EXCLUDE
  434. Specifies the locale(s) to exclude from processing. If not provided, no locales
  435. are excluded.
  436. Example usage::
  437. django-admin makemessages --locale=pt_BR
  438. django-admin makemessages --locale=pt_BR --locale=fr
  439. django-admin makemessages -l pt_BR
  440. django-admin makemessages -l pt_BR -l fr
  441. django-admin makemessages --exclude=pt_BR
  442. django-admin makemessages --exclude=pt_BR --exclude=fr
  443. django-admin makemessages -x pt_BR
  444. django-admin makemessages -x pt_BR -x fr
  445. .. django-admin-option:: --domain DOMAIN, -d DOMAIN
  446. Specifies the domain of the messages files. Supported options are:
  447. * ``django`` for all ``*.py``, ``*.html`` and ``*.txt`` files (default)
  448. * ``djangojs`` for ``*.js`` files
  449. .. django-admin-option:: --symlinks, -s
  450. Follows symlinks to directories when looking for new translation strings.
  451. Example usage::
  452. django-admin makemessages --locale=de --symlinks
  453. .. django-admin-option:: --ignore PATTERN, -i PATTERN
  454. Ignores files or directories matching the given :mod:`glob`-style pattern. Use
  455. multiple times to ignore more.
  456. These patterns are used by default: ``'CVS'``, ``'.*'``, ``'*~'``, ``'*.pyc'``.
  457. Example usage::
  458. django-admin makemessages --locale=en_US --ignore=apps/* --ignore=secret/*.html
  459. .. django-admin-option:: --no-default-ignore
  460. Disables the default values of ``--ignore``.
  461. .. django-admin-option:: --no-wrap
  462. Disables breaking long message lines into several lines in language files.
  463. .. django-admin-option:: --no-location
  464. Suppresses writing '``#: filename:line``’ comment lines in language files.
  465. Using this option makes it harder for technically skilled translators to
  466. understand each message's context.
  467. .. django-admin-option:: --add-location [{full,file,never}]
  468. .. versionadded:: 2.0
  469. Controls ``#: filename:line`` comment lines in language files. If the option
  470. is:
  471. * ``full`` (the default if not given): the lines include both file name and
  472. line number.
  473. * ``file``: the line number is omitted.
  474. * ``never``: the lines are suppressed (same as :option:`--no-location`).
  475. Requires ``gettext`` 0.19 or newer.
  476. .. django-admin-option:: --keep-pot
  477. Prevents deleting the temporary ``.pot`` files generated before creating the
  478. ``.po`` file. This is useful for debugging errors which may prevent the final
  479. language files from being created.
  480. .. seealso::
  481. See :ref:`customizing-makemessages` for instructions on how to customize
  482. the keywords that :djadmin:`makemessages` passes to ``xgettext``.
  483. ``makemigrations``
  484. ------------------
  485. .. django-admin:: makemigrations [app_label [app_label ...]]
  486. Creates new migrations based on the changes detected to your models.
  487. Migrations, their relationship with apps and more are covered in depth in
  488. :doc:`the migrations documentation</topics/migrations>`.
  489. Providing one or more app names as arguments will limit the migrations created
  490. to the app(s) specified and any dependencies needed (the table at the other end
  491. of a ``ForeignKey``, for example).
  492. To add migrations to an app that doesn't have a ``migrations`` directory, run
  493. ``makemigrations`` with the app's ``app_label``.
  494. .. django-admin-option:: --noinput, --no-input
  495. Suppresses all user prompts. If a suppressed prompt cannot be resolved
  496. automatically, the command will exit with error code 3.
  497. .. django-admin-option:: --empty
  498. Outputs an empty migration for the specified apps, for manual editing. This is
  499. for advanced users and should not be used unless you are familiar with the
  500. migration format, migration operations, and the dependencies between your
  501. migrations.
  502. .. django-admin-option:: --dry-run
  503. Shows what migrations would be made without actually writing any migrations
  504. files to disk. Using this option along with ``--verbosity 3`` will also show
  505. the complete migrations files that would be written.
  506. .. django-admin-option:: --merge
  507. Enables fixing of migration conflicts.
  508. .. django-admin-option:: --name NAME, -n NAME
  509. Allows naming the generated migration(s) instead of using a generated name.
  510. .. django-admin-option:: --check
  511. Makes ``makemigrations`` exit with a non-zero status when model changes without
  512. migrations are detected.
  513. ``migrate``
  514. -----------
  515. .. django-admin:: migrate [app_label] [migration_name]
  516. Synchronizes the database state with the current set of models and migrations.
  517. Migrations, their relationship with apps and more are covered in depth in
  518. :doc:`the migrations documentation</topics/migrations>`.
  519. The behavior of this command changes depending on the arguments provided:
  520. * No arguments: All apps have all of their migrations run.
  521. * ``<app_label>``: The specified app has its migrations run, up to the most
  522. recent migration. This may involve running other apps' migrations too, due
  523. to dependencies.
  524. * ``<app_label> <migrationname>``: Brings the database schema to a state where
  525. the named migration is applied, but no later migrations in the same app are
  526. applied. This may involve unapplying migrations if you have previously
  527. migrated past the named migration. Use the name ``zero`` to unapply all
  528. migrations for an app.
  529. .. django-admin-option:: --database DATABASE
  530. Specifies the database to migrate. Defaults to ``default``.
  531. .. django-admin-option:: --fake
  532. Marks the migrations up to the target one (following the rules above) as
  533. applied, but without actually running the SQL to change your database schema.
  534. This is intended for advanced users to manipulate the
  535. current migration state directly if they're manually applying changes;
  536. be warned that using ``--fake`` runs the risk of putting the migration state
  537. table into a state where manual recovery will be needed to make migrations
  538. run correctly.
  539. .. django-admin-option:: --fake-initial
  540. Allows Django to skip an app's initial migration if all database tables with
  541. the names of all models created by all
  542. :class:`~django.db.migrations.operations.CreateModel` operations in that
  543. migration already exist. This option is intended for use when first running
  544. migrations against a database that preexisted the use of migrations. This
  545. option does not, however, check for matching database schema beyond matching
  546. table names and so is only safe to use if you are confident that your existing
  547. schema matches what is recorded in your initial migration.
  548. .. django-admin-option:: --run-syncdb
  549. Allows creating tables for apps without migrations. While this isn't
  550. recommended, the migrations framework is sometimes too slow on large projects
  551. with hundreds of models.
  552. .. django-admin-option:: --noinput, --no-input
  553. Suppresses all user prompts. An example prompt is asking about removing stale
  554. content types.
  555. ``runserver``
  556. -------------
  557. .. django-admin:: runserver [addrport]
  558. Starts a lightweight development Web server on the local machine. By default,
  559. the server runs on port 8000 on the IP address ``127.0.0.1``. You can pass in an
  560. IP address and port number explicitly.
  561. If you run this script as a user with normal privileges (recommended), you
  562. might not have access to start a port on a low port number. Low port numbers
  563. are reserved for the superuser (root).
  564. This server uses the WSGI application object specified by the
  565. :setting:`WSGI_APPLICATION` setting.
  566. DO NOT USE THIS SERVER IN A PRODUCTION SETTING. It has not gone through
  567. security audits or performance tests. (And that's how it's gonna stay. We're in
  568. the business of making Web frameworks, not Web servers, so improving this
  569. server to be able to handle a production environment is outside the scope of
  570. Django.)
  571. The development server automatically reloads Python code for each request, as
  572. needed. You don't need to restart the server for code changes to take effect.
  573. However, some actions like adding files don't trigger a restart, so you'll
  574. have to restart the server in these cases.
  575. If you are using Linux and install `pyinotify`_, kernel signals will be used to
  576. autoreload the server (rather than polling file modification timestamps each
  577. second). This offers better scaling to large projects, reduction in response
  578. time to code modification, more robust change detection, and battery usage
  579. reduction.
  580. .. _pyinotify: https://pypi.python.org/pypi/pyinotify/
  581. When you start the server, and each time you change Python code while the
  582. server is running, the system check framework will check your entire Django
  583. project for some common errors (see the :djadmin:`check` command). If any
  584. errors are found, they will be printed to standard output.
  585. You can run as many concurrent servers as you want, as long as they're on
  586. separate ports. Just execute ``django-admin runserver`` more than once.
  587. Note that the default IP address, ``127.0.0.1``, is not accessible from other
  588. machines on your network. To make your development server viewable to other
  589. machines on the network, use its own IP address (e.g. ``192.168.2.1``) or
  590. ``0.0.0.0`` or ``::`` (with IPv6 enabled).
  591. You can provide an IPv6 address surrounded by brackets
  592. (e.g. ``[200a::1]:8000``). This will automatically enable IPv6 support.
  593. A hostname containing ASCII-only characters can also be used.
  594. If the :doc:`staticfiles</ref/contrib/staticfiles>` contrib app is enabled
  595. (default in new projects) the :djadmin:`runserver` command will be overridden
  596. with its own :ref:`runserver<staticfiles-runserver>` command.
  597. Logging of each request and response of the server is sent to the
  598. :ref:`django-server-logger` logger.
  599. .. django-admin-option:: --noreload
  600. Disables the auto-reloader. This means any Python code changes you make while
  601. the server is running will *not* take effect if the particular Python modules
  602. have already been loaded into memory.
  603. .. django-admin-option:: --nothreading
  604. Disables use of threading in the development server. The server is
  605. multithreaded by default.
  606. .. django-admin-option:: --ipv6, -6
  607. Uses IPv6 for the development server. This changes the default IP address from
  608. ``127.0.0.1`` to ``::1``.
  609. Examples of using different ports and addresses
  610. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  611. Port 8000 on IP address ``127.0.0.1``::
  612. django-admin runserver
  613. Port 8000 on IP address ``1.2.3.4``::
  614. django-admin runserver 1.2.3.4:8000
  615. Port 7000 on IP address ``127.0.0.1``::
  616. django-admin runserver 7000
  617. Port 7000 on IP address ``1.2.3.4``::
  618. django-admin runserver 1.2.3.4:7000
  619. Port 8000 on IPv6 address ``::1``::
  620. django-admin runserver -6
  621. Port 7000 on IPv6 address ``::1``::
  622. django-admin runserver -6 7000
  623. Port 7000 on IPv6 address ``2001:0db8:1234:5678::9``::
  624. django-admin runserver [2001:0db8:1234:5678::9]:7000
  625. Port 8000 on IPv4 address of host ``localhost``::
  626. django-admin runserver localhost:8000
  627. Port 8000 on IPv6 address of host ``localhost``::
  628. django-admin runserver -6 localhost:8000
  629. Serving static files with the development server
  630. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  631. By default, the development server doesn't serve any static files for your site
  632. (such as CSS files, images, things under :setting:`MEDIA_URL` and so forth). If
  633. you want to configure Django to serve static media, read
  634. :doc:`/howto/static-files/index`.
  635. ``sendtestemail``
  636. -----------------
  637. .. django-admin:: sendtestemail [email [email ...]]
  638. Sends a test email (to confirm email sending through Django is working) to the
  639. recipient(s) specified. For example::
  640. django-admin sendtestemail foo@example.com bar@example.com
  641. There are a couple of options, and you may use any combination of them
  642. together:
  643. .. django-admin-option:: --managers
  644. Mails the email addresses specified in :setting:`MANAGERS` using
  645. :meth:`~django.core.mail.mail_managers()`.
  646. .. django-admin-option:: --admins
  647. Mails the email addresses specified in :setting:`ADMINS` using
  648. :meth:`~django.core.mail.mail_admins()`.
  649. ``shell``
  650. ---------
  651. .. django-admin:: shell
  652. Starts the Python interactive interpreter.
  653. .. django-admin-option:: --interface {ipython,bpython,python}, -i {ipython,bpython,python}
  654. Specifies the shell to use. By default, Django will use IPython_ or bpython_ if
  655. either is installed. If both are installed, specify which one you want like so:
  656. IPython::
  657. django-admin shell -i ipython
  658. bpython::
  659. django-admin shell -i bpython
  660. If you have a "rich" shell installed but want to force use of the "plain"
  661. Python interpreter, use ``python`` as the interface name, like so::
  662. django-admin shell -i python
  663. .. _IPython: https://ipython.org/
  664. .. _bpython: https://bpython-interpreter.org/
  665. .. django-admin-option:: --nostartup
  666. Disables reading the startup script for the "plain" Python interpreter. By
  667. default, the script pointed to by the :envvar:`PYTHONSTARTUP` environment
  668. variable or the ``~/.pythonrc.py`` script is read.
  669. .. django-admin-option:: --command COMMAND, -c COMMAND
  670. Lets you pass a command as a string to execute it as Django, like so::
  671. django-admin shell --command="import django; print(django.__version__)"
  672. You can also pass code in on standard input to execute it. For example:
  673. .. code-block:: console
  674. $ django-admin shell <<EOF
  675. > import django
  676. > print(django.__version__)
  677. > EOF
  678. On Windows, the REPL is output due to implementation limits of
  679. :func:`select.select` on that platform.
  680. ``showmigrations``
  681. ------------------
  682. .. django-admin:: showmigrations [app_label [app_label ...]]
  683. Shows all migrations in a project. You can choose from one of two formats:
  684. .. django-admin-option:: --list, -l
  685. Lists all of the apps Django knows about, the migrations available for each
  686. app, and whether or not each migration is applied (marked by an ``[X]`` next to
  687. the migration name).
  688. Apps without migrations are also listed, but have ``(no migrations)`` printed
  689. under them.
  690. This is the default output format.
  691. .. django-admin-option:: --plan, -p
  692. Shows the migration plan Django will follow to apply migrations. Like
  693. ``--list``, applied migrations are marked by an ``[X]``. For a ``--verbosity``
  694. of 2 and above, all dependencies of a migration will also be shown.
  695. ``app_label``\s arguments limit the output, however, dependencies of provided
  696. apps may also be included.
  697. .. django-admin-option:: --database DATABASE
  698. Specifies the database to examine. Defaults to ``default``.
  699. ``sqlflush``
  700. ------------
  701. .. django-admin:: sqlflush
  702. Prints the SQL statements that would be executed for the :djadmin:`flush`
  703. command.
  704. .. django-admin-option:: --database DATABASE
  705. Specifies the database for which to print the SQL. Defaults to ``default``.
  706. ``sqlmigrate``
  707. --------------
  708. .. django-admin:: sqlmigrate app_label migration_name
  709. Prints the SQL for the named migration. This requires an active database
  710. connection, which it will use to resolve constraint names; this means you must
  711. generate the SQL against a copy of the database you wish to later apply it on.
  712. Note that ``sqlmigrate`` doesn't colorize its output.
  713. .. django-admin-option:: --backwards
  714. Generates the SQL for unapplying the migration. By default, the SQL created is
  715. for running the migration in the forwards direction.
  716. .. django-admin-option:: --database DATABASE
  717. Specifies the database for which to generate the SQL. Defaults to ``default``.
  718. ``sqlsequencereset``
  719. --------------------
  720. .. django-admin:: sqlsequencereset app_label [app_label ...]
  721. Prints the SQL statements for resetting sequences for the given app name(s).
  722. Sequences are indexes used by some database engines to track the next available
  723. number for automatically incremented fields.
  724. Use this command to generate SQL which will fix cases where a sequence is out
  725. of sync with its automatically incremented field data.
  726. .. django-admin-option:: --database DATABASE
  727. Specifies the database for which to print the SQL. Defaults to ``default``.
  728. ``squashmigrations``
  729. --------------------
  730. .. django-admin:: squashmigrations app_label [start_migration_name] migration_name
  731. Squashes the migrations for ``app_label`` up to and including ``migration_name``
  732. down into fewer migrations, if possible. The resulting squashed migrations
  733. can live alongside the unsquashed ones safely. For more information,
  734. please read :ref:`migration-squashing`.
  735. When ``start_migration_name`` is given, Django will only include migrations
  736. starting from and including this migration. This helps to mitigate the
  737. squashing limitation of :class:`~django.db.migrations.operations.RunPython` and
  738. :class:`django.db.migrations.operations.RunSQL` migration operations.
  739. .. django-admin-option:: --no-optimize
  740. Disables the optimizer when generating a squashed migration. By default, Django
  741. will try to optimize the operations in your migrations to reduce the size of
  742. the resulting file. Use this option if this process is failing or creating
  743. incorrect migrations, though please also file a Django bug report about the
  744. behavior, as optimization is meant to be safe.
  745. .. django-admin-option:: --noinput, --no-input
  746. Suppresses all user prompts.
  747. .. django-admin-option:: --squashed-name SQUASHED_NAME
  748. .. versionadded:: 2.0
  749. Sets the name of the squashed migration. When omitted, the name is based on the
  750. first and last migration, with ``_squashed_`` in between.
  751. ``startapp``
  752. ------------
  753. .. django-admin:: startapp name [directory]
  754. Creates a Django app directory structure for the given app name in the current
  755. directory or the given destination.
  756. By default the directory created contains a ``models.py`` file and other app
  757. template files. (See the `source`_ for more details.) If only the app
  758. name is given, the app directory will be created in the current working
  759. directory.
  760. If the optional destination is provided, Django will use that existing
  761. directory rather than creating a new one. You can use '.' to denote the current
  762. working directory.
  763. For example::
  764. django-admin startapp myapp /Users/jezdez/Code/myapp
  765. .. _custom-app-and-project-templates:
  766. .. django-admin-option:: --template TEMPLATE
  767. Provides the path to a directory with a custom app template file or a path to a
  768. compressed file (``.tar.gz``, ``.tar.bz2``, ``.tgz``, ``.tbz``, ``.zip``)
  769. containing the app template files.
  770. For example, this would look for an app template in the given directory when
  771. creating the ``myapp`` app::
  772. django-admin startapp --template=/Users/jezdez/Code/my_app_template myapp
  773. Django will also accept URLs (``http``, ``https``, ``ftp``) to compressed
  774. archives with the app template files, downloading and extracting them on the
  775. fly.
  776. For example, taking advantage of GitHub's feature to expose repositories as
  777. zip files, you can use a URL like::
  778. django-admin startapp --template=https://github.com/githubuser/django-app-template/archive/master.zip myapp
  779. .. django-admin-option:: --extension EXTENSIONS, -e EXTENSIONS
  780. Specifies which file extensions in the app template should be rendered with the
  781. template engine. Defaults to ``py``.
  782. .. django-admin-option:: --name FILES, -n FILES
  783. Specifies which files in the app template (in addition to those matching
  784. ``--extension``) should be rendered with the template engine. Defaults to an
  785. empty list.
  786. The :class:`template context <django.template.Context>` used for all matching
  787. files is:
  788. - Any option passed to the ``startapp`` command (among the command's supported
  789. options)
  790. - ``app_name`` -- the app name as passed to the command
  791. - ``app_directory`` -- the full path of the newly created app
  792. - ``camel_case_app_name`` -- the app name in camel case format
  793. - ``docs_version`` -- the version of the documentation: ``'dev'`` or ``'1.x'``
  794. - ``django_version`` -- the version of Django, e.g.``'2.0.3'``
  795. .. _render_warning:
  796. .. warning::
  797. When the app template files are rendered with the Django template
  798. engine (by default all ``*.py`` files), Django will also replace all
  799. stray template variables contained. For example, if one of the Python files
  800. contains a docstring explaining a particular feature related
  801. to template rendering, it might result in an incorrect example.
  802. To work around this problem, you can use the :ttag:`templatetag`
  803. template tag to "escape" the various parts of the template syntax.
  804. In addition, to allow Python template files that contain Django template
  805. language syntax while also preventing packaging systems from trying to
  806. byte-compile invalid ``*.py`` files, template files ending with ``.py-tpl``
  807. will be renamed to ``.py``.
  808. .. _source: https://github.com/django/django/tree/master/django/conf/app_template/
  809. ``startproject``
  810. ----------------
  811. .. django-admin:: startproject name [directory]
  812. Creates a Django project directory structure for the given project name in
  813. the current directory or the given destination.
  814. By default, the new directory contains ``manage.py`` and a project package
  815. (containing a ``settings.py`` and other files). See the `template source`_ for
  816. details.
  817. If only the project name is given, both the project directory and project
  818. package will be named ``<projectname>`` and the project directory
  819. will be created in the current working directory.
  820. If the optional destination is provided, Django will use that existing
  821. directory as the project directory, and create ``manage.py`` and the project
  822. package within it. Use '.' to denote the current working directory.
  823. For example::
  824. django-admin startproject myproject /Users/jezdez/Code/myproject_repo
  825. .. django-admin-option:: --template TEMPLATE
  826. Specifies a directory, file path, or URL of a custom project template. See the
  827. :option:`startapp --template` documentation for examples and usage.
  828. .. django-admin-option:: --extension EXTENSIONS, -e EXTENSIONS
  829. Specifies which file extensions in the project template should be rendered with
  830. the template engine. Defaults to ``py``.
  831. .. django-admin-option:: --name FILES, -n FILES
  832. Specifies which files in the project template (in addition to those matching
  833. ``--extension``) should be rendered with the template engine. Defaults to an
  834. empty list.
  835. The :class:`template context <django.template.Context>` used is:
  836. - Any option passed to the ``startproject`` command (among the command's
  837. supported options)
  838. - ``project_name`` -- the project name as passed to the command
  839. - ``project_directory`` -- the full path of the newly created project
  840. - ``secret_key`` -- a random key for the :setting:`SECRET_KEY` setting
  841. - ``docs_version`` -- the version of the documentation: ``'dev'`` or ``'1.x'``
  842. - ``django_version`` -- the version of Django, e.g.``'2.0.3'``
  843. Please also see the :ref:`rendering warning <render_warning>` as mentioned
  844. for :djadmin:`startapp`.
  845. .. _`template source`: https://github.com/django/django/tree/master/django/conf/project_template/
  846. ``test``
  847. --------
  848. .. django-admin:: test [test_label [test_label ...]]
  849. Runs tests for all installed apps. See :doc:`/topics/testing/index` for more
  850. information.
  851. .. django-admin-option:: --failfast
  852. Stops running tests and reports the failure immediately after a test fails.
  853. .. django-admin-option:: --testrunner TESTRUNNER
  854. Controls the test runner class that is used to execute tests. This value
  855. overrides the value provided by the :setting:`TEST_RUNNER` setting.
  856. .. django-admin-option:: --noinput, --no-input
  857. Suppresses all user prompts. A typical prompt is a warning about deleting an
  858. existing test database.
  859. Test runner options
  860. ~~~~~~~~~~~~~~~~~~~
  861. The ``test`` command receives options on behalf of the specified
  862. :option:`--testrunner`. These are the options of the default test runner:
  863. :class:`~django.test.runner.DiscoverRunner`.
  864. .. django-admin-option:: --keepdb, -k
  865. Preserves the test database between test runs. This has the advantage of
  866. skipping both the create and destroy actions which can greatly decrease the
  867. time to run tests, especially those in a large test suite. If the test database
  868. does not exist, it will be created on the first run and then preserved for each
  869. subsequent run. Any unapplied migrations will also be applied to the test
  870. database before running the test suite.
  871. .. django-admin-option:: --reverse, -r
  872. Sorts test cases in the opposite execution order. This may help in debugging
  873. the side effects of tests that aren't properly isolated. :ref:`Grouping by test
  874. class <order-of-tests>` is preserved when using this option.
  875. .. django-admin-option:: --debug-mode
  876. Sets the :setting:`DEBUG` setting to ``True`` prior to running tests. This may
  877. help troubleshoot test failures.
  878. .. django-admin-option:: --debug-sql, -d
  879. Enables :ref:`SQL logging <django-db-logger>` for failing tests. If
  880. ``--verbosity`` is ``2``, then queries in passing tests are also output.
  881. .. django-admin-option:: --parallel [N]
  882. Runs tests in separate parallel processes. Since modern processors have
  883. multiple cores, this allows running tests significantly faster.
  884. By default ``--parallel`` runs one process per core according to
  885. :func:`multiprocessing.cpu_count()`. You can adjust the number of processes
  886. either by providing it as the option's value, e.g. ``--parallel=4``, or by
  887. setting the ``DJANGO_TEST_PROCESSES`` environment variable.
  888. Django distributes test cases — :class:`unittest.TestCase` subclasses — to
  889. subprocesses. If there are fewer test cases than configured processes, Django
  890. will reduce the number of processes accordingly.
  891. Each process gets its own database. You must ensure that different test cases
  892. don't access the same resources. For instance, test cases that touch the
  893. filesystem should create a temporary directory for their own use.
  894. This option requires the third-party ``tblib`` package to display tracebacks
  895. correctly:
  896. .. code-block:: console
  897. $ pip install tblib
  898. This feature isn't available on Windows. It doesn't work with the Oracle
  899. database backend either.
  900. If you want to use :mod:`pdb` while debugging tests, you must disable parallel
  901. execution (``--parallel=1``). You'll see something like ``bdb.BdbQuit`` if you
  902. don't.
  903. .. warning::
  904. When test parallelization is enabled and a test fails, Django may be
  905. unable to display the exception traceback. This can make debugging
  906. difficult. If you encounter this problem, run the affected test without
  907. parallelization to see the traceback of the failure.
  908. This is a known limitation. It arises from the need to serialize objects
  909. in order to exchange them between processes. See
  910. :ref:`python:pickle-picklable` for details.
  911. .. option:: --tag TAGS
  912. Runs only tests :ref:`marked with the specified tags <topics-tagging-tests>`.
  913. May be specified multiple times and combined with :option:`test --exclude-tag`.
  914. .. option:: --exclude-tag EXCLUDE_TAGS
  915. Excludes tests :ref:`marked with the specified tags <topics-tagging-tests>`.
  916. May be specified multiple times and combined with :option:`test --tag`.
  917. ``testserver``
  918. --------------
  919. .. django-admin:: testserver [fixture [fixture ...]]
  920. Runs a Django development server (as in :djadmin:`runserver`) using data from
  921. the given fixture(s).
  922. For example, this command::
  923. django-admin testserver mydata.json
  924. ...would perform the following steps:
  925. 1. Create a test database, as described in :ref:`the-test-database`.
  926. 2. Populate the test database with fixture data from the given fixtures.
  927. (For more on fixtures, see the documentation for :djadmin:`loaddata` above.)
  928. 3. Runs the Django development server (as in :djadmin:`runserver`), pointed at
  929. this newly created test database instead of your production database.
  930. This is useful in a number of ways:
  931. * When you're writing :doc:`unit tests </topics/testing/overview>` of how your views
  932. act with certain fixture data, you can use ``testserver`` to interact with
  933. the views in a Web browser, manually.
  934. * Let's say you're developing your Django application and have a "pristine"
  935. copy of a database that you'd like to interact with. You can dump your
  936. database to a fixture (using the :djadmin:`dumpdata` command, explained
  937. above), then use ``testserver`` to run your Web application with that data.
  938. With this arrangement, you have the flexibility of messing up your data
  939. in any way, knowing that whatever data changes you're making are only
  940. being made to a test database.
  941. Note that this server does *not* automatically detect changes to your Python
  942. source code (as :djadmin:`runserver` does). It does, however, detect changes to
  943. templates.
  944. .. django-admin-option:: --addrport ADDRPORT
  945. Specifies a different port, or IP address and port, from the default of
  946. ``127.0.0.1:8000``. This value follows exactly the same format and serves
  947. exactly the same function as the argument to the :djadmin:`runserver` command.
  948. Examples:
  949. To run the test server on port 7000 with ``fixture1`` and ``fixture2``::
  950. django-admin testserver --addrport 7000 fixture1 fixture2
  951. django-admin testserver fixture1 fixture2 --addrport 7000
  952. (The above statements are equivalent. We include both of them to demonstrate
  953. that it doesn't matter whether the options come before or after the fixture
  954. arguments.)
  955. To run on 1.2.3.4:7000 with a ``test`` fixture::
  956. django-admin testserver --addrport 1.2.3.4:7000 test
  957. .. django-admin-option:: --noinput, --no-input
  958. Suppresses all user prompts. A typical prompt is a warning about deleting an
  959. existing test database.
  960. Commands provided by applications
  961. =================================
  962. Some commands are only available when the ``django.contrib`` application that
  963. :doc:`implements </howto/custom-management-commands>` them has been
  964. :setting:`enabled <INSTALLED_APPS>`. This section describes them grouped by
  965. their application.
  966. ``django.contrib.auth``
  967. -----------------------
  968. ``changepassword``
  969. ~~~~~~~~~~~~~~~~~~
  970. .. django-admin:: changepassword [<username>]
  971. This command is only available if Django's :doc:`authentication system
  972. </topics/auth/index>` (``django.contrib.auth``) is installed.
  973. Allows changing a user's password. It prompts you to enter a new password twice
  974. for the given user. If the entries are identical, this immediately becomes the
  975. new password. If you do not supply a user, the command will attempt to change
  976. the password whose username matches the current user.
  977. .. django-admin-option:: --database DATABASE
  978. Specifies the database to query for the user. Defaults to ``default``.
  979. Example usage::
  980. django-admin changepassword ringo
  981. ``createsuperuser``
  982. ~~~~~~~~~~~~~~~~~~~
  983. .. django-admin:: createsuperuser
  984. This command is only available if Django's :doc:`authentication system
  985. </topics/auth/index>` (``django.contrib.auth``) is installed.
  986. Creates a superuser account (a user who has all permissions). This is
  987. useful if you need to create an initial superuser account or if you need to
  988. programmatically generate superuser accounts for your site(s).
  989. When run interactively, this command will prompt for a password for
  990. the new superuser account. When run non-interactively, no password
  991. will be set, and the superuser account will not be able to log in until
  992. a password has been manually set for it.
  993. .. django-admin-option:: --username USERNAME
  994. .. django-admin-option:: --email EMAIL
  995. The username and email address for the new account can be supplied by
  996. using the ``--username`` and ``--email`` arguments on the command
  997. line. If either of those is not supplied, ``createsuperuser`` will prompt for
  998. it when running interactively.
  999. .. django-admin-option:: --database DATABASE
  1000. Specifies the database into which the superuser object will be saved.
  1001. You can subclass the management command and override ``get_input_data()`` if you
  1002. want to customize data input and validation. Consult the source code for
  1003. details on the existing implementation and the method's parameters. For example,
  1004. it could be useful if you have a ``ForeignKey`` in
  1005. :attr:`~django.contrib.auth.models.CustomUser.REQUIRED_FIELDS` and want to
  1006. allow creating an instance instead of entering the primary key of an existing
  1007. instance.
  1008. ``django.contrib.contenttypes``
  1009. -------------------------------
  1010. ``remove_stale_contenttypes``
  1011. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1012. .. django-admin:: remove_stale_contenttypes
  1013. This command is only available if Django's :doc:`contenttypes app
  1014. </ref/contrib/contenttypes>` (:mod:`django.contrib.contenttypes`) is installed.
  1015. Deletes stale content types (from deleted models) in your database. Any objects
  1016. that depend on the deleted content types will also be deleted. A list of
  1017. deleted objects will be displayed before you confirm it's okay to proceed with
  1018. the deletion.
  1019. .. django-admin-option:: --database DATABASE
  1020. Specifies the database to use. Defaults to ``default``.
  1021. ``django.contrib.gis``
  1022. ----------------------
  1023. ``ogrinspect``
  1024. ~~~~~~~~~~~~~~
  1025. This command is only available if :doc:`GeoDjango </ref/contrib/gis/index>`
  1026. (``django.contrib.gis``) is installed.
  1027. Please refer to its :djadmin:`description <ogrinspect>` in the GeoDjango
  1028. documentation.
  1029. ``django.contrib.sessions``
  1030. ---------------------------
  1031. ``clearsessions``
  1032. ~~~~~~~~~~~~~~~~~
  1033. .. django-admin:: clearsessions
  1034. Can be run as a cron job or directly to clean out expired sessions.
  1035. ``django.contrib.sitemaps``
  1036. ---------------------------
  1037. ``ping_google``
  1038. ~~~~~~~~~~~~~~~
  1039. This command is only available if the :doc:`Sitemaps framework
  1040. </ref/contrib/sitemaps>` (``django.contrib.sitemaps``) is installed.
  1041. Please refer to its :djadmin:`description <ping_google>` in the Sitemaps
  1042. documentation.
  1043. ``django.contrib.staticfiles``
  1044. ------------------------------
  1045. ``collectstatic``
  1046. ~~~~~~~~~~~~~~~~~
  1047. This command is only available if the :doc:`static files application
  1048. </howto/static-files/index>` (``django.contrib.staticfiles``) is installed.
  1049. Please refer to its :djadmin:`description <collectstatic>` in the
  1050. :doc:`staticfiles </ref/contrib/staticfiles>` documentation.
  1051. ``findstatic``
  1052. ~~~~~~~~~~~~~~
  1053. This command is only available if the :doc:`static files application
  1054. </howto/static-files/index>` (``django.contrib.staticfiles``) is installed.
  1055. Please refer to its :djadmin:`description <findstatic>` in the :doc:`staticfiles
  1056. </ref/contrib/staticfiles>` documentation.
  1057. Default options
  1058. ===============
  1059. .. program:: None
  1060. Although some commands may allow their own custom options, every command
  1061. allows for the following options:
  1062. .. django-admin-option:: --pythonpath PYTHONPATH
  1063. Adds the given filesystem path to the Python `import search path`_. If this
  1064. isn't provided, ``django-admin`` will use the ``PYTHONPATH`` environment
  1065. variable.
  1066. This option is unnecessary in ``manage.py``, because it takes care of setting
  1067. the Python path for you.
  1068. Example usage::
  1069. django-admin migrate --pythonpath='/home/djangoprojects/myproject'
  1070. .. _import search path: http://www.diveintopython3.net/your-first-python-program.html#importsearchpath
  1071. .. django-admin-option:: --settings SETTINGS
  1072. Specifies the settings module to use. The settings module should be in Python
  1073. package syntax, e.g. ``mysite.settings``. If this isn't provided,
  1074. ``django-admin`` will use the ``DJANGO_SETTINGS_MODULE`` environment variable.
  1075. This option is unnecessary in ``manage.py``, because it uses
  1076. ``settings.py`` from the current project by default.
  1077. Example usage::
  1078. django-admin migrate --settings=mysite.settings
  1079. .. django-admin-option:: --traceback
  1080. Displays a full stack trace when a :exc:`~django.core.management.CommandError`
  1081. is raised. By default, ``django-admin`` will show a simple error message when a
  1082. ``CommandError`` occurs and a full stack trace for any other exception.
  1083. Example usage::
  1084. django-admin migrate --traceback
  1085. .. django-admin-option:: --verbosity {0,1,2,3}, -v {0,1,2,3}
  1086. Specifies the amount of notification and debug information that a command
  1087. should print to the console.
  1088. * ``0`` means no output.
  1089. * ``1`` means normal output (default).
  1090. * ``2`` means verbose output.
  1091. * ``3`` means *very* verbose output.
  1092. Example usage::
  1093. django-admin migrate --verbosity 2
  1094. .. django-admin-option:: --no-color
  1095. Disables colorized command output. Some commands format their output to be
  1096. colorized. For example, errors will be printed to the console in red and SQL
  1097. statements will be syntax highlighted.
  1098. Example usage::
  1099. django-admin runserver --no-color
  1100. Extra niceties
  1101. ==============
  1102. .. _syntax-coloring:
  1103. Syntax coloring
  1104. ---------------
  1105. The ``django-admin`` / ``manage.py`` commands will use pretty
  1106. color-coded output if your terminal supports ANSI-colored output. It
  1107. won't use the color codes if you're piping the command's output to
  1108. another program.
  1109. Under Windows, the native console doesn't support ANSI escape sequences so by
  1110. default there is no color output. But you can install the `ANSICON`_
  1111. third-party tool, the Django commands will detect its presence and will make
  1112. use of its services to color output just like on Unix-based platforms.
  1113. The colors used for syntax highlighting can be customized. Django
  1114. ships with three color palettes:
  1115. * ``dark``, suited to terminals that show white text on a black
  1116. background. This is the default palette.
  1117. * ``light``, suited to terminals that show black text on a white
  1118. background.
  1119. * ``nocolor``, which disables syntax highlighting.
  1120. You select a palette by setting a ``DJANGO_COLORS`` environment
  1121. variable to specify the palette you want to use. For example, to
  1122. specify the ``light`` palette under a Unix or OS/X BASH shell, you
  1123. would run the following at a command prompt::
  1124. export DJANGO_COLORS="light"
  1125. You can also customize the colors that are used. Django specifies a
  1126. number of roles in which color is used:
  1127. * ``error`` - A major error.
  1128. * ``notice`` - A minor error.
  1129. * ``success`` - A success.
  1130. * ``warning`` - A warning.
  1131. * ``sql_field`` - The name of a model field in SQL.
  1132. * ``sql_coltype`` - The type of a model field in SQL.
  1133. * ``sql_keyword`` - An SQL keyword.
  1134. * ``sql_table`` - The name of a model in SQL.
  1135. * ``http_info`` - A 1XX HTTP Informational server response.
  1136. * ``http_success`` - A 2XX HTTP Success server response.
  1137. * ``http_not_modified`` - A 304 HTTP Not Modified server response.
  1138. * ``http_redirect`` - A 3XX HTTP Redirect server response other than 304.
  1139. * ``http_not_found`` - A 404 HTTP Not Found server response.
  1140. * ``http_bad_request`` - A 4XX HTTP Bad Request server response other than 404.
  1141. * ``http_server_error`` - A 5XX HTTP Server Error response.
  1142. * ``migrate_heading`` - A heading in a migrations management command.
  1143. * ``migrate_label`` - A migration name.
  1144. Each of these roles can be assigned a specific foreground and
  1145. background color, from the following list:
  1146. * ``black``
  1147. * ``red``
  1148. * ``green``
  1149. * ``yellow``
  1150. * ``blue``
  1151. * ``magenta``
  1152. * ``cyan``
  1153. * ``white``
  1154. Each of these colors can then be modified by using the following
  1155. display options:
  1156. * ``bold``
  1157. * ``underscore``
  1158. * ``blink``
  1159. * ``reverse``
  1160. * ``conceal``
  1161. A color specification follows one of the following patterns:
  1162. * ``role=fg``
  1163. * ``role=fg/bg``
  1164. * ``role=fg,option,option``
  1165. * ``role=fg/bg,option,option``
  1166. where ``role`` is the name of a valid color role, ``fg`` is the
  1167. foreground color, ``bg`` is the background color and each ``option``
  1168. is one of the color modifying options. Multiple color specifications
  1169. are then separated by a semicolon. For example::
  1170. export DJANGO_COLORS="error=yellow/blue,blink;notice=magenta"
  1171. would specify that errors be displayed using blinking yellow on blue,
  1172. and notices displayed using magenta. All other color roles would be
  1173. left uncolored.
  1174. Colors can also be specified by extending a base palette. If you put
  1175. a palette name in a color specification, all the colors implied by that
  1176. palette will be loaded. So::
  1177. export DJANGO_COLORS="light;error=yellow/blue,blink;notice=magenta"
  1178. would specify the use of all the colors in the light color palette,
  1179. *except* for the colors for errors and notices which would be
  1180. overridden as specified.
  1181. .. _ANSICON: http://adoxa.altervista.org/ansicon/
  1182. Bash completion
  1183. ---------------
  1184. If you use the Bash shell, consider installing the Django bash completion
  1185. script, which lives in ``extras/django_bash_completion`` in the Django source
  1186. distribution. It enables tab-completion of ``django-admin`` and
  1187. ``manage.py`` commands, so you can, for instance...
  1188. * Type ``django-admin``.
  1189. * Press [TAB] to see all available options.
  1190. * Type ``sql``, then [TAB], to see all available options whose names start
  1191. with ``sql``.
  1192. See :doc:`/howto/custom-management-commands` for how to add customized actions.
  1193. ==========================================
  1194. Running management commands from your code
  1195. ==========================================
  1196. .. function:: django.core.management.call_command(name, *args, **options)
  1197. To call a management command from code use ``call_command``.
  1198. ``name``
  1199. the name of the command to call or a command object. Passing the name is
  1200. preferred unless the object is required for testing.
  1201. ``*args``
  1202. a list of arguments accepted by the command. Arguments are passed to the
  1203. argument parser, so you can use the same style as you would on the command
  1204. line. For example, ``call_command('flush', '--verbosity=0')``.
  1205. ``**options``
  1206. named options accepted on the command-line. Options are passed to the command
  1207. without triggering the argument parser, which means you'll need to pass the
  1208. correct type. For example, ``call_command('flush', verbosity=0)`` (zero must
  1209. be an integer rather than a string).
  1210. Examples::
  1211. from django.core import management
  1212. from django.core.management.commands import loaddata
  1213. management.call_command('flush', verbosity=0, interactive=False)
  1214. management.call_command('loaddata', 'test_data', verbosity=0)
  1215. management.call_command(loaddata.Command(), 'test_data', verbosity=0)
  1216. Note that command options that take no arguments are passed as keywords
  1217. with ``True`` or ``False``, as you can see with the ``interactive`` option above.
  1218. Named arguments can be passed by using either one of the following syntaxes::
  1219. # Similar to the command line
  1220. management.call_command('dumpdata', '--natural-foreign')
  1221. # Named argument similar to the command line minus the initial dashes and
  1222. # with internal dashes replaced by underscores
  1223. management.call_command('dumpdata', natural_foreign=True)
  1224. # `use_natural_foreign_keys` is the option destination variable
  1225. management.call_command('dumpdata', use_natural_foreign_keys=True)
  1226. Some command options have different names when using ``call_command()`` instead
  1227. of ``django-admin`` or ``manage.py``. For example, ``django-admin
  1228. createsuperuser --no-input`` translates to ``call_command('createsuperuser',
  1229. interactive=False)``. To find what keyword argument name to use for
  1230. ``call_command()``, check the command's source code for the ``dest`` argument
  1231. passed to ``parser.add_argument()``.
  1232. Command options which take multiple options are passed a list::
  1233. management.call_command('dumpdata', exclude=['contenttypes', 'auth'])
  1234. The return value of the ``call_command()`` function is the same as the return
  1235. value of the ``handle()`` method of the command.
  1236. Output redirection
  1237. ==================
  1238. Note that you can redirect standard output and error streams as all commands
  1239. support the ``stdout`` and ``stderr`` options. For example, you could write::
  1240. with open('/path/to/command_output') as f:
  1241. management.call_command('dumpdata', stdout=f)