django-admin.txt 66 KB

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