django-admin.txt 69 KB

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