django-admin.txt 65 KB

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