django-admin.txt 72 KB

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