Django delete superuser
This may be a duplicate, but I couldn’t find the question anywhere, so I’ll go ahead and ask:
Is there a simple way to delete a superuser from the terminal, perhaps analogous to Django’s createsuperuser command?
7 Answers 7
There’s no built in command but you can easily do this from the shell:
In the case of a custom user model it would be:
![]()
An answer for people who did not use Django’s User model instead substituted a Django custom user model.
Now to delete a registered SUPERUSER in our system:
No need to delete superuser. just create another superuser. You can create another superuser with same name as the previous one. I have forgotten the password of the superuser so I create another superuser with the same name as previously.
Как удалить суперпользователя в django
You can use a dash as the fixture name to load input from sys.stdin . For example:
When reading from stdin , the —format option is required to specify the serialization format of the input (e.g., json or xml ).
Loading from stdin is useful with standard input and output redirections. For example:
makemessages ¶
This command doesn’t require configured settings. However, when settings aren’t configured, the command can’t ignore the MEDIA_ROOT and STATIC_ROOT directories or include LOCALE_PATHS .
Updates the message files for all available languages.
—extension EXTENSIONS , -e EXTENSIONS ¶
Specifies a list of file extensions to examine (default: html , txt , py or js if —domain is js ).
Separate multiple extensions with commas or use -e or —extension multiple times:
Specifies the locale(s) to process.
—exclude EXCLUDE , -x EXCLUDE ¶
Specifies the locale(s) to exclude from processing. If not provided, no locales are excluded.
Specifies the domain of the messages files. Supported options are:
- django для *.py , *.html и *.txt файлов (по умолчанию)
- djangojs для файлов *.js
Follows symlinks to directories when looking for new translation strings.
Ignores files or directories matching the given glob -style pattern. Use multiple times to ignore more.
Disables the default values of —ignore .
Disables breaking long message lines into several lines in language files.
Suppresses writing „ #: filename:line ’ comment lines in language files. Using this option makes it harder for technically skilled translators to understand each message’s context.
Controls #: filename:line comment lines in language files. If the option is:
- full (the default if not given): the lines include both file name and line number.
- file : the line number is omitted.
- never : the lines are suppressed (same as —no-location ).
Requires gettext 0.19 or newer.
Prevents deleting the temporary .pot files generated before creating the .po file. This is useful for debugging errors which may prevent the final language files from being created.
makemigrations ¶
To add migrations to an app that doesn’t have a migrations directory, run makemigrations with the app’s app_label .
Suppresses all user prompts. If a suppressed prompt cannot be resolved automatically, the command will exit with error code 3.
Outputs an empty migration for the specified apps, for manual editing. This is for advanced users and should not be used unless you are familiar with the migration format, migration operations, and the dependencies between your migrations.
Shows what migrations would be made without actually writing any migrations files to disk. Using this option along with —verbosity 3 will also show the complete migrations files that would be written.
Enables fixing of migration conflicts.
Allows naming the generated migration(s) instead of using a generated name. The name must be a valid Python identifier .
Generate migration files without Django version and timestamp header.
Makes makemigrations exit with a non-zero status when model changes without migrations are detected.
migrate ¶
- Без аргументов: будет выполнена синхронизация всех приложений.
- <app_label> : Будут выполнены миграции для указанного приложения до самой последней миграции. Это может вызвать миграцию других приложений через зависимости в миграциях.
- <app_label> <migrationname> : Brings the database schema to a state where the named migration is applied, but no later migrations in the same app are applied. This may involve unapplying migrations if you have previously migrated past the named migration. You can use a prefix of the migration name, e.g. 0001 , as long as it’s unique for the given app name. Use the name zero to migrate all the way back i.e. to revert all applied migrations for an app.
When unapplying migrations, all dependent migrations will also be unapplied, regardless of <app_label> . You can use —plan to check which migrations will be unapplied.
Specifies the database to migrate. Defaults to default .
Marks the migrations up to the target one (following the rules above) as applied, but without actually running the SQL to change your database schema.
Allows Django to skip an app’s initial migration if all database tables with the names of all models created by all CreateModel operations in that migration already exist. This option is intended for use when first running migrations against a database that preexisted the use of migrations. This option does not, however, check for matching database schema beyond matching table names and so is only safe to use if you are confident that your existing schema matches what is recorded in your initial migration.
Shows the migration operations that will be performed for the given migrate command.
Allows creating tables for apps without migrations. While this isn’t recommended, the migrations framework is sometimes too slow on large projects with hundreds of models.
Suppresses all user prompts. An example prompt is asking about removing stale content types.
runserver ¶
If you’re using Linux or MacOS and install both pywatchman and the Watchman service, kernel signals will be used to autoreload the server (rather than polling file modification timestamps each second). This offers better performance on large projects, reduced response time after code changes, more robust change detection, and a reduction in power usage. Django supports pywatchman 1.2.0 and higher.
Large directories with many files may cause performance issues
When using Watchman with a project that includes large non-Python directories like node_modules , it’s advisable to ignore this directory for optimal performance. See the watchman documentation for information on how to do this.
The default timeout of Watchman client is 5 seconds. You can change it by setting the DJANGO_WATCHMAN_TIMEOUT environment variable.
Watchman support replaced support for pyinotify .
You can run as many concurrent servers as you want, as long as they’re on separate ports by executing django-admin runserver more than once.
Logging of each request and response of the server is sent to the django.server logger.
Disables the auto-reloader. This means any Python code changes you make while the server is running will not take effect if the particular Python modules have already been loaded into memory.
Disables use of threading in the development server. The server is multithreaded by default.
Uses IPv6 for the development server. This changes the default IP address from 127.0.0.1 to ::1 .
Django delete superuser
This may be a duplicate, but I couldn’t find the question anywhere, so I’ll go ahead and ask:
Is there a simple way to delete a superuser from the terminal, perhaps analogous to Django’s createsuperuser command?
![]()
7 Answers 7
There’s no built in command but you can easily do this from the shell:
No need to delete superuser. just create another superuser. You can create another superuser with same name as the previous one. I have forgotten the password of the superuser so I create another superuser with the same name as previously.
django-admin and manage.py ¶
django-admin is Django’s command-line utility for administrative tasks. This document outlines all it can do.
In addition, manage.py is automatically created in each Django project. It does the same thing as django-admin but also sets the DJANGO_SETTINGS_MODULE environment variable so that it points to your project’s settings.py file.
The django-admin script should be on your system path if you installed Django via pip . If it’s not in your path, ensure you have your virtual environment activated.
Generally, when working on a single Django project, it’s easier to use manage.py than django-admin . If you need to switch between multiple Django settings files, use django-admin with DJANGO_SETTINGS_MODULE or the —settings command line option.
The command-line examples throughout this document use django-admin to be consistent, but any example can use manage.py or python -m django just as well.
Usage¶
command should be one of the commands listed in this document. options , which is optional, should be zero or more of the options available for the given command.
Getting runtime help¶
Run django-admin help to display usage information and a list of the commands provided by each application.
Run django-admin help —commands to display a list of all available commands.
Run django-admin help <command> to display a description of the given command and a list of its available options.
App names¶
Many commands take a list of “app names.” An “app name” is the basename of the package containing your models. For example, if your INSTALLED_APPS contains the string ‘mysite.blog’ , the app name is blog .
Determining the version¶
Run django-admin version to display the current Django version.
The output follows the schema described in PEP 440:
Displaying debug output¶
Use —verbosity , where it is supported, to specify the amount of notification and debug information that django-admin prints to the console.
Available commands¶
check ¶
Uses the system check framework to inspect the entire Django project for common problems.
By default, all apps will be checked. You can check a subset of apps by providing a list of app labels as arguments:
The system check framework performs many different types of checks that are categorized with tags . You can use these tags to restrict the checks performed to just those in a particular category. For example, to perform only models and compatibility checks, run:
Specifies the database to run checks requiring database access:
By default, these checks will not be run.
Lists all available tags.
Activates some additional checks that are only relevant in a deployment setting.
You can use this option in your local development environment, but since your local development settings module may not have many of your production settings, you will probably want to point the check command at a different settings module, either by setting the DJANGO_SETTINGS_MODULE environment variable, or by passing the —settings option:
Or you could run it directly on a production or staging deployment to verify that the correct settings are in use (omitting —settings ). You could even make it part of your integration test suite.
Specifies the message level that will cause the command to exit with a non-zero status. Default is ERROR .
compilemessages ¶
Compiles .po files created by makemessages to .mo files for use with the built-in gettext support. See Internationalization and localization .
—locale LOCALE , -l LOCALE ¶
Specifies the locale(s) to process. If not provided, all locales are processed.
—exclude EXCLUDE , -x EXCLUDE ¶
Specifies the locale(s) to exclude from processing. If not provided, no locales are excluded.
Includes fuzzy translations into compiled files.
Ignores directories matching the given glob -style pattern. Use multiple times to ignore more.
createcachetable ¶
Creates the cache tables for use with the database cache backend using the information from your settings file. See Django’s cache framework for more information.
Specifies the database in which the cache table(s) will be created. Defaults to default .
Prints the SQL that would be run without actually running it, so you can customize it or use the migrations framework.
dbshell ¶
Runs the command-line client for the database engine specified in your ENGINE setting, with the connection parameters specified in your USER , PASSWORD , etc., settings.
- For PostgreSQL, this runs the psql command-line client.
- For MySQL, this runs the mysql command-line client.
- For SQLite, this runs the sqlite3 command-line client.
- For Oracle, this runs the sqlplus command-line client.
This command assumes the programs are on your PATH so that a call to the program name ( psql , mysql , sqlite3 , sqlplus ) will find the program in the right place. There’s no way to specify the location of the program manually.
Specifies the database onto which to open a shell. Defaults to default .
Any arguments following a — divider will be passed on to the underlying command-line client. For example, with PostgreSQL you can use the psql command’s -c flag to execute a raw SQL query directly:
On MySQL/MariaDB, you can do this with the mysql command’s -e flag:
Be aware that not all options set in the OPTIONS part of your database configuration in DATABASES are passed to the command-line client, e.g. ‘isolation_level’ .
diffsettings ¶
Displays differences between the current settings file and Django’s default settings (or another settings file specified by —default ).
Settings that don’t appear in the defaults are followed by «###» . For example, the default settings don’t define ROOT_URLCONF , so ROOT_URLCONF is followed by «###» in the output of diffsettings .
Displays all settings, even if they have Django’s default value. Such settings are prefixed by «###» .
The settings module to compare the current settings against. Leave empty to compare against Django’s default settings.
Specifies the output format. Available values are hash and unified . hash is the default mode that displays the output that’s described above. unified displays the output similar to diff -u . Default settings are prefixed with a minus sign, followed by the changed setting prefixed with a plus sign.
dumpdata ¶
Outputs to standard output all data in the database associated with the named application(s).
If no application name is provided, all installed applications will be dumped.
The output of dumpdata can be used as input for loaddata .
Note that dumpdata uses the default manager on the model for selecting the records to dump. If you’re using a custom manager as the default manager and it filters some of the available records, not all of the objects will be dumped.
Uses Django’s base manager, dumping records which might otherwise be filtered or modified by a custom manager.
Specifies the serialization format of the output. Defaults to JSON. Supported formats are listed in Serialization formats .
Specifies the number of indentation spaces to use in the output. Defaults to None which displays all data on single line.
—exclude EXCLUDE , -e EXCLUDE ¶
Prevents specific applications or models (specified in the form of app_label.ModelName ) from being dumped. If you specify a model name, then only that model will be excluded, rather than the entire application. You can also mix application names and model names.
If you want to exclude multiple applications, pass —exclude more than once:
Specifies the database from which data will be dumped. Defaults to default .
Uses the natural_key() model method to serialize any foreign key and many-to-many relationship to objects of the type that defines the method. If you’re dumping contrib.auth Permission objects or contrib.contenttypes ContentType objects, you should probably use this flag. See the natural keys documentation for more details on this and the next option.
Omits the primary key in the serialized data of this object since it can be calculated during deserialization.
Outputs only the objects specified by a comma separated list of primary keys. This is only available when dumping one model. By default, all the records of the model are output.
—output OUTPUT , -o OUTPUT ¶
Specifies a file to write the serialized data to. By default, the data goes to standard output.
When this option is set and —verbosity is greater than 0 (the default), a progress bar is shown in the terminal.
Fixtures compression¶
The output file can be compressed with one of the bz2 , gz , lzma , or xz formats by ending the filename with the corresponding extension. For example, to output the data as a compressed JSON file:
flush ¶
Removes all data from the database and re-executes any post-synchronization handlers. The table of which migrations have been applied is not cleared.
If you would rather start from an empty database and re-run all migrations, you should drop and recreate the database and then run migrate instead.
Suppresses all user prompts.
Specifies the database to flush. Defaults to default .
inspectdb ¶
Introspects the database tables in the database pointed-to by the NAME setting and outputs a Django model module (a models.py file) to standard output.
You may choose what tables or views to inspect by passing their names as arguments. If no arguments are provided, models are created for views only if the —include-views option is used. Models for partition tables are created on PostgreSQL if the —include-partitions option is used.
Use this if you have a legacy database with which you’d like to use Django. The script will inspect the database and create a model for each table within it.
As you might expect, the created models will have an attribute for every field in the table. Note that inspectdb has a few special cases in its field-name output:
- If inspectdb cannot map a column’s type to a model field type, it’ll use TextField and will insert the Python comment ‘This field type is a guess.’ next to the field in the generated model. The recognized fields may depend on apps listed in INSTALLED_APPS . For example, django.contrib.postgres adds recognition for several PostgreSQL-specific field types.
- If the database column name is a Python reserved word (such as ‘pass’ , ‘class’ or ‘for’ ), inspectdb will append ‘_field’ to the attribute name. For example, if a table has a column ‘for’ , the generated model will have a field ‘for_field’ , with the db_column attribute set to ‘for’ . inspectdb will insert the Python comment ‘Field renamed because it was a Python reserved word.’ next to the field.
This feature is meant as a shortcut, not as definitive model generation. After you run it, you’ll want to look over the generated models yourself to make customizations. In particular, you’ll need to rearrange models’ order, so that models that refer to other models are ordered properly.
Django doesn’t create database defaults when a default is specified on a model field. Similarly, database defaults aren’t translated to model field defaults or detected in any fashion by inspectdb .
By default, inspectdb creates unmanaged models. That is, managed = False in the model’s Meta class tells Django not to manage each table’s creation, modification, and deletion. If you do want to allow Django to manage the table’s lifecycle, you’ll need to change the managed option to True (or remove it because True is its default value).
Database-specific notes¶
Oracle¶
- Models are created for materialized views if —include-views is used.
PostgreSQL¶
- Models are created for foreign tables.
- Models are created for materialized views if —include-views is used.
- Models are created for partition tables if —include-partitions is used.
Specifies the database to introspect. Defaults to default .
If this option is provided, models are also created for partitions.
Only support for PostgreSQL is implemented.
If this option is provided, models are also created for database views.
loaddata ¶
Searches for and loads the contents of the named fixture into the database.
Specifies the database into which the data will be loaded. Defaults to default .
Ignores fields and models that may have been removed since the fixture was originally generated.
Specifies a single app to look for fixtures in rather than looking in all apps.
Specifies the serialization format (e.g., json or xml ) for fixtures read from stdin .
—exclude EXCLUDE , -e EXCLUDE ¶
Excludes loading the fixtures from the given applications and/or models (in the form of app_label or app_label.ModelName ). Use the option multiple times to exclude more than one app or model.
What’s a “fixture”?¶
A fixture is a collection of files that contain the serialized contents of the database. Each fixture has a unique name, and the files that comprise the fixture can be distributed over multiple directories, in multiple applications.
Django will search in three locations for fixtures:
- In the fixtures directory of every installed application
- In any directory named in the FIXTURE_DIRS setting
- In the literal path named by the fixture
Django will load any and all fixtures it finds in these locations that match the provided fixture names.
If the named fixture has a file extension, only fixtures of that type will be loaded. For example:
would only load JSON fixtures called mydata . The fixture extension must correspond to the registered name of a serializer (e.g., json or xml ).
If you omit the extensions, Django will search all available fixture types for a matching fixture. For example:
would look for any fixture of any fixture type called mydata . If a fixture directory contained mydata.json , that fixture would be loaded as a JSON fixture.
The fixtures that are named can include directory components. These directories will be included in the search path. For example:
would search <app_label>/fixtures/foo/bar/mydata.json for each installed application, <dirname>/foo/bar/mydata.json for each directory in FIXTURE_DIRS , and the literal path foo/bar/mydata.json .
When fixture files are processed, the data is saved to the database as is. Model defined save() methods are not called, and any pre_save or post_save signals will be called with raw=True since the instance only contains attributes that are local to the model. You may, for example, want to disable handlers that access related fields that aren’t present during fixture loading and would otherwise raise an exception:
You could also write a decorator to encapsulate this logic:
Just be aware that this logic will disable the signals whenever fixtures are deserialized, not just during loaddata .
Note that the order in which fixture files are processed is undefined. However, all fixture data is installed as a single transaction, so data in one fixture can reference data in another fixture. If the database backend supports row-level constraints, these constraints will be checked at the end of the transaction.
The dumpdata command can be used to generate input for loaddata .
Compressed fixtures¶
Fixtures may be compressed in zip , gz , bz2 , lzma , or xz format. For example:
would look for any of mydata.json , mydata.json.zip , mydata.json.gz , mydata.json.bz2 , mydata.json.lzma , or mydata.json.xz . The first file contained within a compressed archive is used.
Note that if two fixtures with the same name but different fixture type are discovered (for example, if mydata.json and mydata.xml.gz were found in the same fixture directory), fixture installation will be aborted, and any data installed in the call to loaddata will be removed from the database.
MySQL with MyISAM and fixtures
The MyISAM storage engine of MySQL doesn’t support transactions or constraints, so if you use MyISAM, you won’t get validation of fixture data, or a rollback if multiple transaction files are found.
Support for XZ archives ( .xz ) and LZMA archives ( .lzma ) was added.
Database-specific fixtures¶
If you’re in a multi-database setup, you might have fixture data that you want to load onto one database, but not onto another. In this situation, you can add a database identifier into the names of your fixtures.
For example, if your DATABASES setting has a ‘master’ database defined, name the fixture mydata.master.json or mydata.master.json.gz and the fixture will only be loaded when you specify you want to load data into the master database.
Loading fixtures from stdin ¶
You can use a dash as the fixture name to load input from sys.stdin . For example:
When reading from stdin , the —format option is required to specify the serialization format of the input (e.g., json or xml ).
Loading from stdin is useful with standard input and output redirections. For example:
makemessages ¶
Runs over the entire source tree of the current directory and pulls out all strings marked for translation. It creates (or updates) a message file in the conf/locale (in the Django tree) or locale (for project and application) directory. After making changes to the messages files you need to compile them with compilemessages for use with the builtin gettext support. See the i18n documentation for details.
This command doesn’t require configured settings. However, when settings aren’t configured, the command can’t ignore the MEDIA_ROOT and STATIC_ROOT directories or include LOCALE_PATHS .
Updates the message files for all available languages.
—extension EXTENSIONS , -e EXTENSIONS ¶
Specifies a list of file extensions to examine (default: html , txt , py or js if —domain is js ).
Separate multiple extensions with commas or use -e or —extension multiple times:
Specifies the locale(s) to process.
—exclude EXCLUDE , -x EXCLUDE ¶
Specifies the locale(s) to exclude from processing. If not provided, no locales are excluded.
Specifies the domain of the messages files. Supported options are:
- django for all *.py , *.html and *.txt files (default)
- djangojs for *.js files
Follows symlinks to directories when looking for new translation strings.
Ignores files or directories matching the given glob -style pattern. Use multiple times to ignore more.
Disables the default values of —ignore .
Disables breaking long message lines into several lines in language files.
Suppresses writing ‘ #: filename:line ’ comment lines in language files. Using this option makes it harder for technically skilled translators to understand each message’s context.
Controls #: filename:line comment lines in language files. If the option is:
- full (the default if not given): the lines include both file name and line number.
- file : the line number is omitted.
- never : the lines are suppressed (same as —no-location ).
Requires gettext 0.19 or newer.
Prevents deleting the temporary .pot files generated before creating the .po file. This is useful for debugging errors which may prevent the final language files from being created.
See Customizing the makemessages command for instructions on how to customize the keywords that makemessages passes to xgettext .
makemigrations ¶
Creates new migrations based on the changes detected to your models. Migrations, their relationship with apps and more are covered in depth in the migrations documentation .
Providing one or more app names as arguments will limit the migrations created to the app(s) specified and any dependencies needed (the table at the other end of a ForeignKey , for example).
To add migrations to an app that doesn’t have a migrations directory, run makemigrations with the app’s app_label .
Suppresses all user prompts. If a suppressed prompt cannot be resolved automatically, the command will exit with error code 3.
Outputs an empty migration for the specified apps, for manual editing. This is for advanced users and should not be used unless you are familiar with the migration format, migration operations, and the dependencies between your migrations.
Shows what migrations would be made without actually writing any migrations files to disk. Using this option along with —verbosity 3 will also show the complete migrations files that would be written.
Enables fixing of migration conflicts.
Allows naming the generated migration(s) instead of using a generated name. The name must be a valid Python identifier .
Generate migration files without Django version and timestamp header.
Makes makemigrations exit with a non-zero status when model changes without migrations are detected.
Support for calling makemigrations without an active database connection was added. In that case, check for a consistent migration history is skipped.
migrate ¶
Synchronizes the database state with the current set of models and migrations. Migrations, their relationship with apps and more are covered in depth in the migrations documentation .
The behavior of this command changes depending on the arguments provided:
- No arguments: All apps have all of their migrations run.
- <app_label> : The specified app has its migrations run, up to the most recent migration. This may involve running other apps’ migrations too, due to dependencies.
- <app_label> <migrationname> : Brings the database schema to a state where the named migration is applied, but no later migrations in the same app are applied. This may involve unapplying migrations if you have previously migrated past the named migration. You can use a prefix of the migration name, e.g. 0001 , as long as it’s unique for the given app name. Use the name zero to migrate all the way back i.e. to revert all applied migrations for an app.
When unapplying migrations, all dependent migrations will also be unapplied, regardless of <app_label> . You can use —plan to check which migrations will be unapplied.
Specifies the database to migrate. Defaults to default .
Marks the migrations up to the target one (following the rules above) as applied, but without actually running the SQL to change your database schema.
This is intended for advanced users to manipulate the current migration state directly if they’re manually applying changes; be warned that using —fake runs the risk of putting the migration state table into a state where manual recovery will be needed to make migrations run correctly.
Allows Django to skip an app’s initial migration if all database tables with the names of all models created by all CreateModel operations in that migration already exist. This option is intended for use when first running migrations against a database that preexisted the use of migrations. This option does not, however, check for matching database schema beyond matching table names and so is only safe to use if you are confident that your existing schema matches what is recorded in your initial migration.
Shows the migration operations that will be performed for the given migrate command.
Allows creating tables for apps without migrations. While this isn’t recommended, the migrations framework is sometimes too slow on large projects with hundreds of models.
Suppresses all user prompts. An example prompt is asking about removing stale content types.
Makes migrate exit with a non-zero status when unapplied migrations are detected.
runserver ¶
Starts a lightweight development web server on the local machine. By default, the server runs on port 8000 on the IP address 127.0.0.1 . You can pass in an IP address and port number explicitly.
If you run this script as a user with normal privileges (recommended), you might not have access to start a port on a low port number. Low port numbers are reserved for the superuser (root).
This server uses the WSGI application object specified by the WSGI_APPLICATION setting.
DO NOT USE THIS SERVER IN A PRODUCTION SETTING. It has not gone through security audits or performance tests. (And that’s how it’s gonna stay. We’re in the business of making web frameworks, not web servers, so improving this server to be able to handle a production environment is outside the scope of Django.)
The development server automatically reloads Python code for each request, as needed. You don’t need to restart the server for code changes to take effect. However, some actions like adding files don’t trigger a restart, so you’ll have to restart the server in these cases.
If you’re using Linux or MacOS and install both pywatchman and the Watchman service, kernel signals will be used to autoreload the server (rather than polling file modification timestamps each second). This offers better performance on large projects, reduced response time after code changes, more robust change detection, and a reduction in power usage. Django supports pywatchman 1.2.0 and higher.
Large directories with many files may cause performance issues
When using Watchman with a project that includes large non-Python directories like node_modules , it’s advisable to ignore this directory for optimal performance. See the watchman documentation for information on how to do this.
The default timeout of Watchman client is 5 seconds. You can change it by setting the DJANGO_WATCHMAN_TIMEOUT environment variable.
When you start the server, and each time you change Python code while the server is running, the system check framework will check your entire Django project for some common errors (see the check command). If any errors are found, they will be printed to standard output. You can use the —skip-checks option to skip running system checks.
You can run as many concurrent servers as you want, as long as they’re on separate ports by executing django-admin runserver more than once.
Note that the default IP address, 127.0.0.1 , is not accessible from other machines on your network. To make your development server viewable to other machines on the network, use its own IP address (e.g. 192.168.2.1 ) or 0.0.0.0 or :: (with IPv6 enabled).
You can provide an IPv6 address surrounded by brackets (e.g. [200a::1]:8000 ). This will automatically enable IPv6 support.
A hostname containing ASCII-only characters can also be used.
If the staticfiles contrib app is enabled (default in new projects) the runserver command will be overridden with its own runserver command.
Logging of each request and response of the server is sent to the django.server logger.
Disables the auto-reloader. This means any Python code changes you make while the server is running will not take effect if the particular Python modules have already been loaded into memory.
Disables use of threading in the development server. The server is multithreaded by default.
Uses IPv6 for the development server. This changes the default IP address from 127.0.0.1 to ::1 .
Support for the —skip-checks option was added.
Examples of using different ports and addresses¶
Port 8000 on IP address 127.0.0.1 :
Port 8000 on IP address 1.2.3.4 :
Port 7000 on IP address 127.0.0.1 :
Port 7000 on IP address 1.2.3.4 :
Port 8000 on IPv6 address ::1 :
Port 7000 on IPv6 address ::1 :
Port 7000 on IPv6 address 2001:0db8:1234:5678::9 :
Port 8000 on IPv4 address of host localhost :
Port 8000 on IPv6 address of host localhost :
Serving static files with the development server¶
By default, the development server doesn’t serve any static files for your site (such as CSS files, images, things under MEDIA_URL and so forth). If you want to configure Django to serve static media, read How to manage static files (e.g. images, JavaScript, CSS) .
sendtestemail ¶
Sends a test email (to confirm email sending through Django is working) to the recipient(s) specified. For example:
There are a couple of options, and you may use any combination of them together:
Mails the email addresses specified in MANAGERS using mail_managers() .
Mails the email addresses specified in ADMINS using mail_admins() .
shell ¶
Starts the Python interactive interpreter.
Specifies the shell to use. By default, Django will use IPython or bpython if either is installed. If both are installed, specify which one you want like so:
If you have a “rich” shell installed but want to force use of the “plain” Python interpreter, use python as the interface name, like so:
Disables reading the startup script for the “plain” Python interpreter. By default, the script pointed to by the PYTHONSTARTUP environment variable or the
/.pythonrc.py script is read.
—command COMMAND , -c COMMAND ¶
Lets you pass a command as a string to execute it as Django, like so:
You can also pass code in on standard input to execute it. For example:
On Windows, the REPL is output due to implementation limits of select.select() on that platform.
showmigrations ¶
Shows all migrations in a project. You can choose from one of two formats:
Lists all of the apps Django knows about, the migrations available for each app, and whether or not each migration is applied (marked by an [X] next to the migration name). For a —verbosity of 2 and above, the applied datetimes are also shown.
Apps without migrations are also listed, but have (no migrations) printed under them.
This is the default output format.
Shows the migration plan Django will follow to apply migrations. Like —list , applied migrations are marked by an [X] . For a —verbosity of 2 and above, all dependencies of a migration will also be shown.
app_label s arguments limit the output, however, dependencies of provided apps may also be included.
Specifies the database to examine. Defaults to default .
sqlflush ¶
Prints the SQL statements that would be executed for the flush command.
Specifies the database for which to print the SQL. Defaults to default .
sqlmigrate ¶
Prints the SQL for the named migration. This requires an active database connection, which it will use to resolve constraint names; this means you must generate the SQL against a copy of the database you wish to later apply it on.
Note that sqlmigrate doesn’t colorize its output.
Generates the SQL for unapplying the migration. By default, the SQL created is for running the migration in the forwards direction.
Specifies the database for which to generate the SQL. Defaults to default .
sqlsequencereset ¶
Prints the SQL statements for resetting sequences for the given app name(s).
Sequences are indexes used by some database engines to track the next available number for automatically incremented fields.
Use this command to generate SQL which will fix cases where a sequence is out of sync with its automatically incremented field data.
Specifies the database for which to print the SQL. Defaults to default .
squashmigrations ¶
Squashes the migrations for app_label up to and including migration_name down into fewer migrations, if possible. The resulting squashed migrations can live alongside the unsquashed ones safely. For more information, please read Squashing migrations .
When start_migration_name is given, Django will only include migrations starting from and including this migration. This helps to mitigate the squashing limitation of RunPython and django.db.migrations.operations.RunSQL migration operations.
Disables the optimizer when generating a squashed migration. By default, Django will try to optimize the operations in your migrations to reduce the size of the resulting file. Use this option if this process is failing or creating incorrect migrations, though please also file a Django bug report about the behavior, as optimization is meant to be safe.
Suppresses all user prompts.
Sets the name of the squashed migration. When omitted, the name is based on the first and last migration, with _squashed_ in between.
Generate squashed migration file without Django version and timestamp header.
startapp ¶
Creates a Django app directory structure for the given app name in the current directory or the given destination.
By default, the new directory contains a models.py file and other app template files. If only the app name is given, the app directory will be created in the current working directory.
If the optional destination is provided, Django will use that existing directory rather than creating a new one. You can use ‘.’ to denote the current working directory.
Provides the path to a directory with a custom app template file, or a path to an uncompressed archive ( .tar ) or a compressed archive ( .tar.gz , .tar.bz2 , .tar.xz , .tar.lzma , .tgz , .tbz2 , .txz , .tlz , .zip ) containing the app template files.
For example, this would look for an app template in the given directory when creating the myapp app:
Django will also accept URLs ( http , https , ftp ) to compressed archives with the app template files, downloading and extracting them on the fly.
For example, taking advantage of GitHub’s feature to expose repositories as zip files, you can use a URL like:
Specifies which file extensions in the app template should be rendered with the template engine. Defaults to py .
—name FILES , -n FILES ¶
Specifies which files in the app template (in addition to those matching —extension ) should be rendered with the template engine. Defaults to an empty list.
—exclude DIRECTORIES , -x DIRECTORIES ¶
Specifies which directories in the app template should be excluded, in addition to .git and __pycache__ . If this option is not provided, directories named __pycache__ or starting with . will be excluded.
The template context used for all matching files is:
- Any option passed to the startapp command (among the command’s supported options)
- app_name – the app name as passed to the command
- app_directory – the full path of the newly created app
- camel_case_app_name – the app name in camel case format
- docs_version – the version of the documentation: ‘dev’ or ‘1.x’
- django_version – the version of Django, e.g. ‘2.0.3’
When the app template files are rendered with the Django template engine (by default all *.py files), Django will also replace all stray template variables contained. For example, if one of the Python files contains a docstring explaining a particular feature related to template rendering, it might result in an incorrect example.
To work around this problem, you can use the templatetag template tag to “escape” the various parts of the template syntax.
In addition, to allow Python template files that contain Django template language syntax while also preventing packaging systems from trying to byte-compile invalid *.py files, template files ending with .py-tpl will be renamed to .py .
startproject ¶
Creates a Django project directory structure for the given project name in the current directory or the given destination.
By default, the new directory contains manage.py and a project package (containing a settings.py and other files).
If only the project name is given, both the project directory and project package will be named <projectname> and the project directory will be created in the current working directory.
If the optional destination is provided, Django will use that existing directory as the project directory, and create manage.py and the project package within it. Use ‘.’ to denote the current working directory.
Specifies a directory, file path, or URL of a custom project template. See the startapp —template documentation for examples and usage.
—extension EXTENSIONS , -e EXTENSIONS ¶
Specifies which file extensions in the project template should be rendered with the template engine. Defaults to py .
—name FILES , -n FILES ¶
Specifies which files in the project template (in addition to those matching —extension ) should be rendered with the template engine. Defaults to an empty list.
—exclude DIRECTORIES , -x DIRECTORIES ¶
Specifies which directories in the project template should be excluded, in addition to .git and __pycache__ . If this option is not provided, directories named __pycache__ or starting with . will be excluded.
- Any option passed to the startproject command (among the command’s supported options)
- project_name – the project name as passed to the command
- project_directory – the full path of the newly created project
- secret_key – a random key for the SECRET_KEY setting
- docs_version – the version of the documentation: ‘dev’ or ‘1.x’
- django_version – the version of Django, e.g. ‘2.0.3’
Please also see the rendering warning as mentioned for startapp .
Runs tests for all installed apps. See Testing in Django for more information.
Stops running tests and reports the failure immediately after a test fails.
Controls the test runner class that is used to execute tests. This value overrides the value provided by the TEST_RUNNER setting.
Suppresses all user prompts. A typical prompt is a warning about deleting an existing test database.
Test runner options¶
The test command receives options on behalf of the specified —testrunner . These are the options of the default test runner: DiscoverRunner .
Preserves the test database between test runs. This has the advantage of skipping both the create and destroy actions which can greatly decrease the time to run tests, especially those in a large test suite. If the test database does not exist, it will be created on the first run and then preserved for each subsequent run. Unless the MIGRATE test setting is False , any unapplied migrations will also be applied to the test database before running the test suite.
Randomizes the order of tests before running them. This can help detect tests that aren’t properly isolated. The test order generated by this option is a deterministic function of the integer seed given. When no seed is passed, a seed is chosen randomly and printed to the console. To repeat a particular test order, pass a seed. The test orders generated by this option preserve Django’s guarantees on test order . They also keep tests grouped by test case class.
The shuffled orderings also have a special consistency property useful when narrowing down isolation issues. Namely, for a given seed and when running a subset of tests, the new order will be the original shuffling restricted to the smaller set. Similarly, when adding tests while keeping the seed the same, the order of the original tests will be the same in the new order.
Sorts test cases in the opposite execution order. This may help in debugging the side effects of tests that aren’t properly isolated. Grouping by test class is preserved when using this option. This can be used in conjunction with —shuffle to reverse the order for a particular seed.
Sets the DEBUG setting to True prior to running tests. This may help troubleshoot test failures.
Enables SQL logging for failing tests. If —verbosity is 2 , then queries in passing tests are also output.
—parallel [N] ¶ DJANGO_TEST_PROCESSES ¶
Runs tests in separate parallel processes. Since modern processors have multiple cores, this allows running tests significantly faster.
Using —parallel without a value, or with the value auto , runs one test process per core according to multiprocessing.cpu_count() . You can override this by passing the desired number of processes, e.g. —parallel 4 , or by setting the DJANGO_TEST_PROCESSES environment variable.
Django distributes test cases — unittest.TestCase subclasses — to subprocesses. If there are fewer test cases than configured processes, Django will reduce the number of processes accordingly.
Each process gets its own database. You must ensure that different test cases don’t access the same resources. For instance, test cases that touch the filesystem should create a temporary directory for their own use.
If you have test classes that cannot be run in parallel, you can use SerializeMixin to run them sequentially. See Enforce running test classes sequentially .
This option requires the third-party tblib package to display tracebacks correctly:
This feature isn’t available on Windows. It doesn’t work with the Oracle database backend either.
If you want to use pdb while debugging tests, you must disable parallel execution ( —parallel=1 ). You’ll see something like bdb.BdbQuit if you don’t.
When test parallelization is enabled and a test fails, Django may be unable to display the exception traceback. This can make debugging difficult. If you encounter this problem, run the affected test without parallelization to see the traceback of the failure.
This is a known limitation. It arises from the need to serialize objects in order to exchange them between processes. See What can be pickled and unpickled? for details.
Support for the value auto was added.
Runs only tests marked with the specified tags . May be specified multiple times and combined with test —exclude-tag .
Tests that fail to load are always considered matching.
In older versions, tests that failed to load did not match tags.
Excludes tests marked with the specified tags . May be specified multiple times and combined with test —tag .
Runs test methods and classes matching test name patterns, in the same way as unittest’s -k option . Can be specified multiple times.
Spawns a pdb debugger at each test error or failure. If you have it installed, ipdb is used instead.
Discards output ( stdout and stderr ) for passing tests, in the same way as unittest’s —buffer option .
Django automatically calls faulthandler.enable() when starting the tests, which allows it to print a traceback if the interpreter crashes. Pass —no-faulthandler to disable this behavior.
Outputs timings, including database setup and total run time.
testserver ¶
Runs a Django development server (as in runserver ) using data from the given fixture(s).
For example, this command:
…would perform the following steps:
- Create a test database, as described in The test database .
- Populate the test database with fixture data from the given fixtures. (For more on fixtures, see the documentation for loaddata above.)
- Runs the Django development server (as in runserver ), pointed at this newly created test database instead of your production database.
This is useful in a number of ways:
- When you’re writing unit tests of how your views act with certain fixture data, you can use testserver to interact with the views in a web browser, manually.
- Let’s say you’re developing your Django application and have a “pristine” copy of a database that you’d like to interact with. You can dump your database to a fixture (using the dumpdata command, explained above), then use testserver to run your web application with that data. With this arrangement, you have the flexibility of messing up your data in any way, knowing that whatever data changes you’re making are only being made to a test database.
Note that this server does not automatically detect changes to your Python source code (as runserver does). It does, however, detect changes to templates.
Specifies a different port, or IP address and port, from the default of 127.0.0.1:8000 . This value follows exactly the same format and serves exactly the same function as the argument to the runserver command.
To run the test server on port 7000 with fixture1 and fixture2 :
(The above statements are equivalent. We include both of them to demonstrate that it doesn’t matter whether the options come before or after the fixture arguments.)
To run on 1.2.3.4:7000 with a test fixture:
Suppresses all user prompts. A typical prompt is a warning about deleting an existing test database.
Commands provided by applications¶
Some commands are only available when the django.contrib application that implements them has been enabled . This section describes them grouped by their application.
django.contrib.auth ¶
changepassword ¶
This command is only available if Django’s authentication system ( django.contrib.auth ) is installed.
Allows changing a user’s password. It prompts you to enter a new password twice for the given user. If the entries are identical, this immediately becomes the new password. If you do not supply a user, the command will attempt to change the password whose username matches the current user.
Specifies the database to query for the user. Defaults to default .
createsuperuser ¶
This command is only available if Django’s authentication system ( django.contrib.auth ) is installed.
Creates a superuser account (a user who has all permissions). This is useful if you need to create an initial superuser account or if you need to programmatically generate superuser accounts for your site(s).
When run interactively, this command will prompt for a password for the new superuser account. When run non-interactively, you can provide a password by setting the DJANGO_SUPERUSER_PASSWORD environment variable. Otherwise, no password will be set, and the superuser account will not be able to log in until a password has been manually set for it.
In non-interactive mode, the USERNAME_FIELD and required fields (listed in REQUIRED_FIELDS ) fall back to DJANGO_SUPERUSER_<uppercase_field_name> environment variables, unless they are overridden by a command line argument. For example, to provide an email field, you can use DJANGO_SUPERUSER_EMAIL environment variable.
Suppresses all user prompts. If a suppressed prompt cannot be resolved automatically, the command will exit with error code 1.
—username USERNAME ¶ —email EMAIL ¶
The username and email address for the new account can be supplied by using the —username and —email arguments on the command line. If either of those is not supplied, createsuperuser will prompt for it when running interactively.
Specifies the database into which the superuser object will be saved.
You can subclass the management command and override get_input_data() if you want to customize data input and validation. Consult the source code for details on the existing implementation and the method’s parameters. For example, it could be useful if you have a ForeignKey in REQUIRED_FIELDS and want to allow creating an instance instead of entering the primary key of an existing instance.
django.contrib.contenttypes ¶
remove_stale_contenttypes ¶
This command is only available if Django’s contenttypes app ( django.contrib.contenttypes ) is installed.
Deletes stale content types (from deleted models) in your database. Any objects that depend on the deleted content types will also be deleted. A list of deleted objects will be displayed before you confirm it’s okay to proceed with the deletion.
Specifies the database to use. Defaults to default .
Deletes stale content types including ones from previously installed apps that have been removed from INSTALLED_APPS . Defaults to False .
django.contrib.gis ¶
ogrinspect ¶
This command is only available if GeoDjango ( django.contrib.gis ) is installed.
Please refer to its description in the GeoDjango documentation.
django.contrib.sessions ¶
clearsessions ¶
Can be run as a cron job or directly to clean out expired sessions.
django.contrib.sitemaps ¶
ping_google ¶
This command is only available if the Sitemaps framework ( django.contrib.sitemaps ) is installed.
Please refer to its description in the Sitemaps documentation.
django.contrib.staticfiles ¶
collectstatic ¶
This command is only available if the static files application ( django.contrib.staticfiles ) is installed.
Please refer to its description in the staticfiles documentation.
findstatic ¶
This command is only available if the static files application ( django.contrib.staticfiles ) is installed.
Please refer to its description in the staticfiles documentation.
Default options¶
Although some commands may allow their own custom options, every command allows for the following options by default:
Adds the given filesystem path to the Python import search path. If this isn’t provided, django-admin will use the PYTHONPATH environment variable.
This option is unnecessary in manage.py , because it takes care of setting the Python path for you.
Specifies the settings module to use. The settings module should be in Python package syntax, e.g. mysite.settings . If this isn’t provided, django-admin will use the DJANGO_SETTINGS_MODULE environment variable.
This option is unnecessary in manage.py , because it uses settings.py from the current project by default.
Displays a full stack trace when a CommandError is raised. By default, django-admin will show an error message when a CommandError occurs and a full stack trace for any other exception.
This option is ignored by runserver .
Specifies the amount of notification and debug information that a command should print to the console.
- 0 means no output.
- 1 means normal output (default).
- 2 means verbose output.
- 3 means very verbose output.
This option is ignored by runserver .
Disables colorized command output. Some commands format their output to be colorized. For example, errors will be printed to the console in red and SQL statements will be syntax highlighted.
Forces colorization of the command output if it would otherwise be disabled as discussed in Syntax coloring . For example, you may want to pipe colored output to another command.
Skips running system checks prior to running the command. This option is only available if the requires_system_checks command attribute is not an empty list or tuple.
Extra niceties¶
Syntax coloring¶
The django-admin / manage.py commands will use pretty color-coded output if your terminal supports ANSI-colored output. It won’t use the color codes if you’re piping the command’s output to another program unless the —force-color option is used.
Windows support¶
On Windows 10, the Windows Terminal application, VS Code, and PowerShell (where virtual terminal processing is enabled) allow colored output, and are supported by default.
Under Windows, the legacy cmd.exe native console doesn’t support ANSI escape sequences so by default there is no color output. In this case either of two third-party libraries are needed:
Install colorama, a Python package that translates ANSI color codes into Windows API calls. Django commands will detect its presence and will make use of its services to color output just like on Unix-based platforms. colorama can be installed via pip:
Install ANSICON, a third-party tool that allows cmd.exe to process ANSI color codes. Django commands will detect its presence and will make use of its services to color output just like on Unix-based platforms.
Other modern terminal environments on Windows, that support terminal colors, but which are not automatically detected as supported by Django, may “fake” the installation of ANSICON by setting the appropriate environmental variable, ANSICON=»on» .
Updated support for syntax coloring on Windows.
Custom colors¶
The colors used for syntax highlighting can be customized. Django ships with three color palettes:
- dark , suited to terminals that show white text on a black background. This is the default palette.
- light , suited to terminals that show black text on a white background.
- nocolor , which disables syntax highlighting.
You select a palette by setting a DJANGO_COLORS environment variable to specify the palette you want to use. For example, to specify the light palette under a Unix or OS/X BASH shell, you would run the following at a command prompt:
You can also customize the colors that are used. Django specifies a number of roles in which color is used:
- error — A major error.
- notice — A minor error.
- success — A success.
- warning — A warning.
- sql_field — The name of a model field in SQL.
- sql_coltype — The type of a model field in SQL.
- sql_keyword — An SQL keyword.
- sql_table — The name of a model in SQL.
- http_info — A 1XX HTTP Informational server response.
- http_success — A 2XX HTTP Success server response.
- http_not_modified — A 304 HTTP Not Modified server response.
- http_redirect — A 3XX HTTP Redirect server response other than 304.
- http_not_found — A 404 HTTP Not Found server response.
- http_bad_request — A 4XX HTTP Bad Request server response other than 404.
- http_server_error — A 5XX HTTP Server Error response.
- migrate_heading — A heading in a migrations management command.
- migrate_label — A migration name.
Each of these roles can be assigned a specific foreground and background color, from the following list:
- black
- red
- green
- yellow
- blue
- magenta
- cyan
- white
Each of these colors can then be modified by using the following display options:
- bold
- underscore
- blink
- reverse
- conceal
A color specification follows one of the following patterns:
- role=fg
- role=fg/bg
- role=fg,option,option
- role=fg/bg,option,option
where role is the name of a valid color role, fg is the foreground color, bg is the background color and each option is one of the color modifying options. Multiple color specifications are then separated by a semicolon. For example:
would specify that errors be displayed using blinking yellow on blue, and notices displayed using magenta. All other color roles would be left uncolored.
Colors can also be specified by extending a base palette. If you put a palette name in a color specification, all the colors implied by that palette will be loaded. So:
would specify the use of all the colors in the light color palette, except for the colors for errors and notices which would be overridden as specified.
Bash completion¶
If you use the Bash shell, consider installing the Django bash completion script, which lives in extras/django_bash_completion in the Django source distribution. It enables tab-completion of django-admin and manage.py commands, so you can, for instance…
- Type django-admin .
- Press [TAB] to see all available options.
- Type sql , then [TAB], to see all available options whose names start with sql .
See How to create custom django-admin commands for how to add customized actions.
Running management commands from your code¶
To call a management command from code use call_command .
name the name of the command to call or a command object. Passing the name is preferred unless the object is required for testing. *args a list of arguments accepted by the command. Arguments are passed to the argument parser, so you can use the same style as you would on the command line. For example, call_command(‘flush’, ‘—verbosity=0’) . **options named options accepted on the command-line. Options are passed to the command without triggering the argument parser, which means you’ll need to pass the correct type. For example, call_command(‘flush’, verbosity=0) (zero must be an integer rather than a string).
Note that command options that take no arguments are passed as keywords with True or False , as you can see with the interactive option above.
Named arguments can be passed by using either one of the following syntaxes:
Some command options have different names when using call_command() instead of django-admin or manage.py . For example, django-admin createsuperuser —no-input translates to call_command(‘createsuperuser’, interactive=False) . To find what keyword argument name to use for call_command() , check the command’s source code for the dest argument passed to parser.add_argument() .
Command options which take multiple options are passed a list:
The return value of the call_command() function is the same as the return value of the handle() method of the command.
Output redirection¶
Note that you can redirect standard output and error streams as all commands support the stdout and stderr options. For example, you could write:
Использование системы аутентификации Django ¶
В этом документе объясняется использование системы аутентификации Django в ее конфигурации по умолчанию. Эта конфигурация была разработана для удовлетворения наиболее распространенных потребностей проекта, для обработки достаточно широкого круга задач и для тщательной реализации паролей и разрешений. Для проектов, в которых требуется проверка подлинности, отличная от стандартной, Django поддерживает обширное расширение и настройку проверки подлинности.
Аутентификация Django обеспечивает как аутентификацию, так и авторизацию вместе и обычно называется системой аутентификации, поскольку эти функции в некоторой степени связаны.
User объекты ¶
User объекты являются ядром системы аутентификации. Обычно они представляют людей, взаимодействующих с вашим сайтом, и используются для включения таких вещей, как ограничение доступа, регистрация профилей пользователей, связывание контента с создателями и т. Д. В структуре аутентификации Django существует только один класс пользователей, т. ‘superusers’ Е. ‘staff’ Пользователи- администраторы являются просто объектами пользователей с набор специальных атрибутов, а не различных классов пользовательских объектов.
Основные атрибуты пользователя по умолчанию:
Для получения полной справки см. Следующую документацию, более ориентированную на задачи. full API documentation
Создание пользователей ¶
Самый простой способ создать пользователей — использовать включенную create_user() вспомогательную функцию:
Если у вас установлен администратор Django, вы также можете создавать пользователей в интерактивном режиме .
Создание суперпользователей ¶
Создайте суперпользователей с помощью createsuperuser команды:
Вам будет предложено ввести пароль. После того, как вы введете один, пользователь будет создан немедленно. Если вы не укажете параметры —username или —email , вам будет предложено ввести эти значения.
Смена паролей ¶
Django не хранит необработанные (в виде открытого текста) пароли в модели пользователя, а только хэш (подробности см. В документации по управлению паролями ). По этой причине не пытайтесь напрямую манипулировать атрибутом пароля пользователя. Вот почему при создании пользователя используется вспомогательная функция.
Чтобы изменить пароль пользователя, у вас есть несколько вариантов:
manage.py changepassword *username* предлагает способ изменения пароля пользователя из командной строки. Он предлагает вам изменить пароль данного пользователя, который вы должны ввести дважды. Если они оба совпадают, новый пароль будет немедленно изменен. Если вы не укажете пользователя, команда попытается изменить пароль, имя пользователя которого совпадает с текущим пользователем системы.
Вы также можете изменить пароль программно, используя set_password() :
Если у вас установлен администратор Django, вы также можете изменить пароли пользователей на страницах администратора системы аутентификации .
Django также предоставляет представления и формы, которые можно использовать, чтобы позволить пользователям изменять свои собственные пароли.
Изменение пароля пользователя приведет к выходу из всех его сеансов. См. Подробности в разделе « Аннулирование сеанса при смене пароля» .
Аутентификация пользователей ¶
Используйте authenticate() для проверки набора учетных данных. Он принимает учетные данные в качестве аргументов ключевого слова username и password для случая по умолчанию проверяет их на соответствие каждому бэкэнду аутентификации и возвращает User объект, если учетные данные действительны для бэкэнда. Если учетные данные недействительны для какого-либо бэкэнда или если бэкэнд возникает PermissionDenied , он возвращается None . Например:
request — необязательный параметр, HttpRequest который передается в authenticate() методе бэкэндов аутентификации.
Это низкоуровневый способ аутентификации набора учетных данных; например, он используется RemoteUserMiddleware . Если вы не пишете свою собственную систему аутентификации, вы, вероятно, не будете ее использовать. Скорее, если вы ищете способ войти в систему, используйте расширение LoginView .
Разрешения и авторизация ¶
Django имеет встроенную систему разрешений. Он позволяет назначать разрешения конкретным пользователям и группам пользователей.
Он используется сайтом администратора Django, но вы можете использовать его в своем собственном коде.
Сайт администратора Django использует следующие разрешения:
- Доступ к просмотру объектов ограничен пользователями с разрешением «просмотр» или «изменение» для этого типа объекта.
- Доступ для просмотра формы «добавления» и добавления объекта ограничен пользователями с разрешением «добавить» для этого типа объекта.
- Доступ для просмотра списка изменений, просмотра формы «изменения» и изменения объекта ограничен пользователями с разрешением «изменение» для этого типа объекта.
- Доступ для удаления объекта ограничен пользователями с разрешением на «удаление» для этого типа объекта.
Разрешения можно установить не только для каждого типа объекта, но и для конкретного экземпляра объекта. Используя has_view_permission() , has_add_permission() , has_change_permission() и has_delete_permission() методы , предоставляемые ModelAdmin классом, можно настроить разрешения для различных экземпляров объектов одного и того же типа.
User объекты имеют два поля типа «многие ко многим»: groups и user_permissions . User объекты могут обращаться к своим связанным объектам так же, как и к любой другой модели Django :
Разрешения по умолчанию ¶
Когда django.contrib.auth он указан в ваших INSTALLED_APPS настройках, он гарантирует, что четыре разрешения по умолчанию — добавление, изменение, удаление и просмотр — созданы для каждой модели Django, определенной в одном из ваших установленных приложений.
Эти разрешения будут созданы при запуске ; первый раз , когда вы запускаете после добавления к , разрешения по умолчанию будут созданы для всех ранее установленных моделей, а также для любых новых моделей устанавливаются в то время. После этого он будет создавать разрешения по умолчанию для новых моделей при каждом запуске (функция, создающая разрешения, подключена к сигналу). manage.py migrate migrate django.contrib.auth INSTALLED_APPS manage.py migrate post_migrate
Предполагая, что у вас есть приложение с именами и моделью , для проверки основных разрешений вы должны использовать: app_label foo Bar
- Добавлять: user.has_perm(‘foo.add_bar’)
- менять: user.has_perm(‘foo.change_bar’)
- Удалить: user.has_perm(‘foo.delete_bar’)
- Посмотреть: user.has_perm(‘foo.view_bar’)
К Permission модели редко обращаются напрямую.
Группы ¶
django.contrib.auth.models.Group модели — это общий способ категоризации пользователей, чтобы вы могли применять к ним разрешения или какой-либо другой ярлык. Пользователь может принадлежать к любому количеству групп.
Пользователь в группе автоматически получает разрешения, предоставленные этой группе. Например, если у группы есть разрешение , любой пользователь в этой группе будет иметь это разрешение. Site editors can_edit_home_page
Помимо разрешений, группы — это удобный способ категоризации пользователей, чтобы дать им определенную метку или расширенную функциональность. Например, вы можете создать группу и написать код, который мог бы, скажем, предоставить им доступ к части вашего сайта, предназначенной только для членов, или отправлять им сообщения электронной почты только для членов. ‘Special users’
Программное создание разрешений ¶
Хотя пользовательские разрешения могут быть определены в Meta классе модели , вы также можете создавать разрешения напрямую. Например, вы можете создать can_publish разрешение для BlogPost модели в myapp :
Затем разрешение может быть назначено объекту User через его user_permissions атрибут или Group через его permissions атрибут.
Прокси-моделям нужен собственный тип контента
Если вы хотите создать разрешения для прокси-модели , перейдите for_concrete_model=False к, ContentTypeManager.get_for_model() чтобы получить соответствующие ContentType :
Кеширование разрешений ¶
В ModelBackend кэширует разрешения на пользовательском объекте после первого времени они должны быть выбраны для проверки прав доступа. Обычно это нормально для цикла запрос-ответ, поскольку разрешения обычно не проверяются сразу после их добавления (например, в админке). Если вы добавляете разрешения и проверяете их сразу после этого, например, в тесте или представлении, самым простым решением является повторное получение пользователя из базы данных. Например:
Прокси-модели ¶
Прокси-модели работают точно так же, как и конкретные модели. Разрешения создаются с использованием собственного типа содержимого прокси-модели. Прокси-модели не наследуют разрешения конкретной модели, которую они подклассифицируют:
Аутентификация в веб-запросах ¶
Django использует сеансы и промежуточное ПО для подключения системы аутентификации . request objects
Они предоставляют request.user атрибут для каждого запроса, который представляет текущего пользователя. Если текущий пользователь не вошел в систему, для этого атрибута будет установлен экземпляр AnonymousUser , в противном случае он будет экземпляром User .
Вы можете отличить их друг от друга is_authenticated следующим образом:
Как авторизовать пользователя ¶
Если у вас есть аутентифицированный пользователь, которого вы хотите присоединить к текущему сеансу — это делается с помощью login() функции.
login ( запрос , пользователь , бэкэнд = Нет ) ¶
Для входа пользователя в систему из представления используйте login() . Он принимает HttpRequest предмет и User предмет. login() сохраняет идентификатор пользователя в сеансе, используя структуру сеанса Django.
Обратите внимание, что любой набор данных во время анонимного сеанса сохраняется в сеансе после входа пользователя в систему.
В этом примере показано, как можно использовать authenticate() и login() :
Выбор серверной части аутентификации ¶
Когда пользователь входит в систему, идентификатор пользователя и серверная часть, которая использовалась для аутентификации, сохраняются в сеансе пользователя. Это позволяет тому же бэкэнду аутентификации получать данные пользователя в будущем запросе. Бэкэнд аутентификации для сохранения в сеансе выбирается следующим образом:
- Используйте значение необязательного backend аргумента, если он предоставлен.
- Используйте значение user.backend атрибута, если оно есть. Это позволяет создавать пары authenticate() и login() : authenticate() устанавливает user.backend атрибут для возвращаемого им пользовательского объекта.
- Используйте backend in AUTHENTICATION_BACKENDS , если он только один.
- В противном случае вызовите исключение.
В случаях 1 и 2 значение backend аргумента или user.backend атрибута должно быть пунктирной строкой пути импорта (например, в AUTHENTICATION_BACKENDS ), а не фактическим внутренним классом.
Как выйти из системы ¶
Чтобы выйти из системы пользователя, который вошел в систему через django.contrib.auth.login() , используйте django.contrib.auth.logout() в вашем представлении. Он принимает HttpRequest объект и не имеет возвращаемого значения. Пример:
Обратите внимание, что logout() не вызывает ошибок, если пользователь не вошел в систему.
Когда вы звоните logout() , данные сеанса для текущего запроса полностью очищаются. Все существующие данные удаляются. Это сделано для того, чтобы другой человек не мог использовать тот же веб-браузер для входа в систему и доступа к данным сеанса предыдущего пользователя. Если вы хотите поместить в сеанс что-либо, что будет доступно пользователю сразу после выхода из системы, сделайте это после вызова django.contrib.auth.logout() .
Ограничение доступа для авторизованных пользователей ¶
Необработанный способ ¶
Самый простой способ ограничить доступ к страницам — это проверить request.user.is_authenticated и перенаправить на страницу входа:
… Или отобразить сообщение об ошибке:
login_required Декоратор ¶
В качестве ярлыка можно использовать удобный login_required() декоратор:
- Если пользователь не вошел в систему, выполните перенаправление на settings.LOGIN_URL , передав текущий абсолютный путь в строке запроса. Пример: /accounts/login/?next=/polls/3/ .
- Если пользователь вошел в систему, выполните просмотр в обычном режиме. Код просмотра может предполагать, что пользователь вошел в систему.
По умолчанию путь, на который должен быть перенаправлен пользователь после успешной аутентификации, сохраняется в параметре строки запроса с именем «next» . Если вы предпочитаете использовать другое имя для этого параметра, login_required() принимает необязательный redirect_field_name параметр:
Обратите внимание, что если вы укажете значение для redirect_field_name , вам, скорее всего, также потребуется настроить свой шаблон входа в систему, поскольку переменная контекста шаблона, которая хранит путь перенаправления, будет использовать значение в redirect_field_name качестве своего ключа, а не «next» (по умолчанию).
login_required() также принимает необязательный login_url параметр. Пример:
Обратите внимание: если вы не укажете login_url параметр, вам необходимо убедиться, что представление settings.LOGIN_URL и ваше представление входа в систему правильно связаны. Например, используя значения по умолчанию, добавьте следующие строки в свой URLconf:
settings.LOGIN_URL Также принимает имена функций просмотра и именованные шаблоны URL . Это позволяет вам свободно переназначать представление входа в систему в вашем URLconf без необходимости обновлять настройки.
login_required Декоратор не проверяет is_active флаг на пользователя, но по умолчанию AUTHENTICATION_BACKENDS отклонять неактивных пользователей.
Если вы пишете собственные представления для администратора Django (или нуждаетесь в той же проверке авторизации, что и встроенные представления), вы можете найти django.contrib.admin.views.decorators.staff_member_required() декоратор полезной альтернативой login_required() .
LoginRequired Mixin ¶
При использовании представлений на основе классов можно добиться того же поведения, что и при login_required использовании LoginRequiredMixin . Этот миксин должен находиться в крайнем левом положении в списке наследования.
Если представление использует этот миксин, все запросы неаутентифицированных пользователей будут перенаправлены на страницу входа или отображать ошибку HTTP 403 Forbidden, в зависимости от raise_exception параметра.
Вы можете установить любой из параметров, AccessMixin чтобы настроить обработку неавторизованных пользователей:
Как и login_required декоратор, этот миксин НЕ проверяет is_active флаг пользователя, но по умолчанию AUTHENTICATION_BACKENDS отклоняет неактивных пользователей.
Ограничение доступа для авторизованных пользователей, прошедших тест ¶
Чтобы ограничить доступ на основе определенных разрешений или какого-либо другого теста, вы должны сделать то же самое, что описано в предыдущем разделе.
Вы можете запустить свой тест request.user прямо в представлении. Например, это представление проверяет, есть ли у пользователя электронная почта в желаемом домене, и если нет, перенаправляет на страницу входа:
В качестве ярлыка вы можете использовать удобный user_passes_test декоратор, который выполняет перенаправление при возврате вызываемого объекта False :
user_passes_test() принимает обязательный аргумент: вызываемый User объект, который принимает объект и возвращает, True если пользователю разрешено просматривать страницу. Обратите внимание, что user_passes_test() не проверяет автоматически, что User это не анонимно.
user_passes_test() принимает два необязательных аргумента:
login_url Позволяет указать URL-адрес, на который будут перенаправлены пользователи, не прошедшие тест. Это может быть страница входа в систему, которая используется по умолчанию, settings.LOGIN_URL если вы ее не указали. redirect_field_name То же, что и для login_required() . Установка его на None удаление его из URL-адреса, что вы можете сделать, если вы перенаправляете пользователей, которые не прошли тест, на страницу без входа, где нет «следующей страницы».
При использовании представлений на основе классов вы можете использовать UserPassesTestMixin для этого.
Вы должны переопределить test_func() метод класса, чтобы обеспечить выполняемый тест. Кроме того, вы можете установить любой из параметров AccessMixin для настройки обработки неавторизованных пользователей:
Вы также можете переопределить get_test_func() метод, чтобы миксин использовал для своих проверок функцию с другим именем (вместо test_func() ).
Из-за того, как UserPassesTestMixin реализован способ , вы не можете складывать их в свой список наследования. Следующее НЕ работает:
Если TestMixin1 бы позвонил super() и принял во внимание этот результат, TestMixin1 больше не работал бы автономно.
permission_required Декоратор ¶
Относительно распространенная задача — проверить, есть ли у пользователя конкретное разрешение. По этой причине Django предоставляет ярлык для этого случая: permission_required() декоратор .:
Как и в случае с has_perm() методом, имена разрешений принимают форму (т. Е. Для разрешения модели в приложении). «<app label>.<permission codename>» polls.add_choice polls
Декоратор также может принимать итерацию разрешений, и в этом случае пользователь должен иметь все разрешения для доступа к представлению.
Обратите внимание, что permission_required() также принимает необязательный login_url параметр:
Как и в login_required() декораторе, по login_url умолчанию settings.LOGIN_URL .
Если raise_exception задан параметр, декоратор поднимется PermissionDenied , предлагая представление 403 (HTTP Forbidden) вместо перенаправления на страницу входа.
Если вы хотите использовать, raise_exception но также даете своим пользователям возможность сначала войти в систему, вы можете добавить login_required() декоратор:
Это также позволяет избежать петлю переадресации , если LoginView «S redirect_authenticated_user=True и вошедшие в системе пользователя не имеет все необходимые разрешения.
PermissionRequiredMixin Mixin ¶
Чтобы применить проверки разрешений к представлениям на основе классов , вы можете использовать PermissionRequiredMixin :
Этот миксин, как и permission_required декоратор, проверяет, имеет ли пользователь, обращающийся к представлению, все заданные разрешения. Вы должны указать разрешение (или итерацию разрешений) с помощью permission_required параметра:
Вы можете установить любой из параметров, AccessMixin чтобы настроить обработку неавторизованных пользователей.
Вы также можете переопределить эти методы:
Возвращает итерацию имен разрешений, используемых миксином. По умолчанию используется permission_required атрибут, при необходимости преобразованный в кортеж.
Возвращает логическое значение, обозначающее, есть ли у текущего пользователя разрешение на выполнение декорированного представления. По умолчанию это возвращает результат вызова has_perms() со списком разрешений, возвращенным get_permission_required() .
Перенаправление неавторизованных запросов в представлениях на основе классов ¶
Чтобы упростить обработку ограничений доступа в представлениях на основе классов , AccessMixin можно использовать для настройки поведения представления при отказе в доступе. Прошедшим проверку пользователям отказано в доступе с ответом HTTP 403 Forbidden. Анонимные пользователи перенаправляются на страницу входа или получают ответ HTTP 403 Forbidden, в зависимости от raise_exception атрибута.
класс AccessMixin ¶ login_url ¶
Возвращаемое значение по умолчанию для get_login_url() . По умолчанию, None в этом случае get_login_url() возвращается к settings.LOGIN_URL .
Возвращаемое значение по умолчанию для get_permission_denied_message() . По умолчанию пустая строка.
Возвращаемое значение по умолчанию для get_redirect_field_name() . По умолчанию «next» .
Если для этого атрибута установлено значение True , возникает PermissionDenied исключение, когда условия не выполняются. Когда False (по умолчанию) анонимные пользователи перенаправляются на страницу входа.
Возвращает URL-адрес, на который будут перенаправлены пользователи, не прошедшие тест. Возвращает, login_url если установлено, или в settings.LOGIN_URL противном случае.
Когда raise_exception есть True , этот метод можно использовать для управления сообщением об ошибке, передаваемым обработчику ошибок для отображения пользователю. permission_denied_message По умолчанию возвращает атрибут.
Возвращает имя параметра запроса, который будет содержать URL-адрес, на который пользователь должен быть перенаправлен после успешного входа в систему. Если вы установите это значение None , параметр запроса не будет добавлен. redirect_field_name По умолчанию возвращает атрибут.
В зависимости от значения raise_exception , метод либо вызывает PermissionDenied исключение, либо перенаправляет пользователя к login_url , необязательно включая, redirect_field_name если он установлен.
Аннулирование сессии при смене пароля ¶
Если ваш метод AUTH_USER_MODEL наследуется от AbstractBaseUser собственного get_session_auth_hash() метода или реализует его , сеансы аутентификации будут включать хэш, возвращаемый этой функцией. В данном AbstractBaseUser случае это HMAC поля пароля. Django проверяет, что хэш в сеансе для каждого запроса совпадает с хешем, вычисленным во время запроса. Это позволяет пользователю выйти из всех своих сеансов, изменив свой пароль.
Представления изменения пароля по умолчанию, включенные в Django, PasswordChangeView и user_change_password представление в django.contrib.auth администраторе обновляют сеанс с использованием нового хэша пароля, чтобы пользователь, меняющий собственный пароль, не выходил из системы. Если у вас есть настраиваемое представление изменения пароля и вы хотите иметь аналогичное поведение, используйте update_session_auth_hash() функцию.
update_session_auth_hash ( запрос , пользователь ) ¶
Эта функция принимает текущий запрос и обновленный объект пользователя, из которого будет получен новый хэш сеанса, и соответствующим образом обновляет хеш сеанса. Он также меняет ключ сеанса, чтобы украденный файл cookie сеанса был признан недействительным.
Поскольку get_session_auth_hash() основан на SECRET_KEY , обновление вашего сайта для использования нового секрета приведет к аннулированию всех существующих сеансов.
Представления аутентификации ¶
Django предоставляет несколько представлений, которые вы можете использовать для обработки входа в систему, выхода из системы и управления паролями. Они используют стандартные формы авторизации, но вы также можете передавать свои собственные формы.
Django не предоставляет шаблонов по умолчанию для представлений аутентификации. Вы должны создать свои собственные шаблоны для представлений, которые хотите использовать. Контекст шаблона задокументирован в каждом представлении, см. Все представления проверки подлинности .
Использование представлений ¶
Существуют разные методы реализации этих представлений в вашем проекте. Самый простой способ — включить предоставленный URLconf django.contrib.auth.urls в ваш собственный URLconf, например:
Это будет включать следующие шаблоны URL:
Представления предоставляют имя URL-адреса для более удобного использования. См. Документацию по URL для получения подробной информации об использовании именованных шаблонов URL.
Если вам нужен больший контроль над своими URL-адресами, вы можете указать конкретное представление в своем URLconf:
У представлений есть необязательные аргументы, которые вы можете использовать для изменения поведения представления. Например, если вы хотите изменить имя шаблона, которое использует представление, вы можете указать template_name аргумент. Способ сделать это — предоставить аргументы ключевого слова в URLconf, они будут переданы в представление. Например:
Все представления основаны на классах , что позволяет легко настраивать их путем создания подклассов.
Все представления аутентификации ¶
Это список всех django.contrib.auth представлений. Подробнее о реализации см. Использование представлений .
Имя URL: login
См. Документацию по URL для получения подробной информации об использовании именованных шаблонов URL.
Атрибуты:
template_name : Имя шаблона, отображаемого для представления, используемого для входа пользователя в систему. По умолчанию registration/login.html .
redirect_field_name : Имя GET поля, содержащего URL-адрес для перенаправления после входа в систему. По умолчанию next .
authentication_form : Вызываемый объект (обычно класс формы), используемый для аутентификации. По умолчанию AuthenticationForm .
extra_context : Словарь данных контекста, который будет добавлен к данным контекста по умолчанию, передаваемым в шаблон.
redirect_authenticated_user : Логическое значение, которое определяет, будут ли перенаправлены аутентифицированные пользователи, обращающиеся к странице входа в систему, как если бы они только что успешно вошли в систему. По умолчанию False .
Если вы включите эту функцию redirect_authenticated_user , другие веб-сайты смогут определять, аутентифицированы ли их посетители на вашем сайте, запрашивая URL-адреса перенаправления на файлы изображений на вашем веб-сайте. Чтобы избежать утечки информации из социальных сетей , разместите все изображения и значок в отдельном домене.
Включение redirect_authenticated_user также может привести к возникновению цикла перенаправления при использовании permission_required() декоратора, если не используется raise_exception параметр.
success_url_allowed_hosts : A set хостов, в дополнение к request.get_host() которым можно безопасно перенаправить после входа в систему. По умолчанию пустой set .
Вот что LoginView делает:
- При вызове через GET , он отображает форму входа в систему, которая отправляет POST на тот же URL-адрес. Подробнее об этом чуть позже.
- При вызове POST с использованием учетных данных, представленных пользователем, он пытается войти в систему. Если вход в систему прошел успешно, представление перенаправляется на URL-адрес, указанный в next . Если next не указан, выполняется перенаправление на settings.LOGIN_REDIRECT_URL (по умолчанию /accounts/profile/ ). Если логин не удался, он повторно отображает форму входа.
Вы обязаны предоставить html для шаблона входа, который вызывается registration/login.html по умолчанию. В этот шаблон передаются четыре контекстные переменные шаблона:
- form : Form Объект, представляющий AuthenticationForm .
- next : URL-адрес для перенаправления после успешного входа в систему. Это также может содержать строку запроса.
- site : Текущее значение в Site соответствии с SITE_ID настройкой. Если у вас не установлен фреймворк сайта, будет установлен экземпляр RequestSite , который получает имя сайта и домен из текущего HttpRequest .
- site_name : Псевдоним для site.name . Если у вас не установлена платформа сайта, будет установлено значение request.META[‘SERVER_NAME’] . Дополнительные сведения о сайтах см. В разделе « Структура сайтов» .
Если вы предпочитаете не вызывать шаблон registration/login.html , вы можете передать template_name параметр с помощью дополнительных аргументов as_view методу в вашем URLconf. Например, эта строка URLconf будет использовать myapp/login.html вместо этого:
Вы также можете указать имя GET поля, которое содержит URL-адрес для перенаправления после входа в систему redirect_field_name . По умолчанию это поле называется next .
Вот образец registration/login.html шаблона, который вы можете использовать в качестве отправной точки. Предполагается, что у вас есть base.html шаблон, определяющий content блок:
Если у вас настроена проверка подлинности (см. Настройка проверки подлинности ), вы можете использовать настраиваемую форму проверки подлинности, установив authentication_form атрибут. Эта форма должна принимать request аргумент ключевого слова в своем __init__() методе и предоставлять get_user() метод, который возвращает объект аутентифицированного пользователя (этот метод вызывается только после успешной проверки формы).
Выполняет выход пользователя из системы.
Имя URL: logout
Атрибуты:
- next_page : URL-адрес для перенаправления после выхода из системы. По умолчанию settings.LOGOUT_REDIRECT_URL .
- template_name : Полное имя шаблона, отображаемого после выхода пользователя из системы. По умолчанию registration/logged_out.html .
- redirect_field_name : Имя GET поля, содержащего URL-адрес для перенаправления после выхода из системы. По умолчанию next . Переопределяет next_page URL-адрес, если передан данный GET параметр.
- extra_context : Словарь данных контекста, который будет добавлен к данным контекста по умолчанию, передаваемым в шаблон.
- success_url_allowed_hosts : A set хостов, в дополнение к request.get_host() которым можно безопасно перенаправить после выхода из системы. По умолчанию пустой set .
Контекст шаблона:
- title : Строка «Вышел из системы», локализована.
- site : Текущее значение в Site соответствии с SITE_ID настройкой. Если у вас не установлен фреймворк сайта, будет установлен экземпляр RequestSite , который получает имя сайта и домен из текущего HttpRequest .
- site_name : Псевдоним для site.name . Если у вас не установлена платформа сайта, будет установлено значение request.META[‘SERVER_NAME’] . Дополнительные сведения о сайтах см. В разделе « Структура сайтов» .
Выполняет выход пользователя из системы, затем перенаправляет на страницу входа.
Имя URL-адреса: URL-адрес по умолчанию не указан
Необязательные аргументы:
- login_url : URL-адрес страницы входа, на которую выполняется перенаправление. По умолчанию, settings.LOGIN_URL если не указан.
Имя URL: password_change
Позволяет пользователю изменить свой пароль.
Атрибуты:
- template_name : Полное имя шаблона, который будет использоваться для отображения формы изменения пароля. По умолчанию, registration/password_change_form.html если не указан.
- success_url : URL-адрес для перенаправления после успешной смены пароля. По умолчанию ‘password_change_done’ .
- form_class : Настраиваемая форма «смены пароля», которая должна принимать user аргумент ключевого слова. Форма отвечает за фактическое изменение пароля пользователя. По умолчанию PasswordChangeForm .
- extra_context : Словарь данных контекста, который будет добавлен к данным контекста по умолчанию, передаваемым в шаблон.
Контекст шаблона:
- form : Форма смены пароля (см. form_class Выше).
Имя URL: password_change_done
Страница, отображаемая после того, как пользователь изменил свой пароль.
Атрибуты:
- template_name : Полное имя используемого шаблона. По умолчанию, registration/password_change_done.html если не указан.
- extra_context : Словарь данных контекста, который будет добавлен к данным контекста по умолчанию, передаваемым в шаблон.
Имя URL: password_reset
Позволяет пользователю сбросить свой пароль, создав одноразовую ссылку, которую можно использовать для сброса пароля, и отправив эту ссылку на зарегистрированный адрес электронной почты пользователя.
Если указанный адрес электронной почты не существует в системе, это представление не отправит электронное письмо, но пользователь также не получит сообщения об ошибке. Это предотвращает утечку информации потенциальным злоумышленникам. Если вы хотите предоставить сообщение об ошибке в этом случае, вы можете создать подкласс PasswordResetForm и использовать form_class атрибут.
Имейте в виду, что отправка электронного письма требует дополнительного времени, поэтому вы можете быть уязвимы для атаки по времени перечисления адресов электронной почты из-за разницы между продолжительностью запроса на сброс для существующего адреса электронной почты и продолжительностью запроса на сброс для несуществующего адреса электронной почты. . Чтобы уменьшить накладные расходы, вы можете использовать сторонний пакет, который позволяет отправлять электронные письма асинхронно, например django-mailer .
Пользователи, отмеченные непригодным для использования паролем (см. set_unusable_password() Не разрешено запрашивать сброс пароля, чтобы предотвратить неправильное использование при использовании внешнего источника аутентификации, такого как LDAP. Обратите внимание, что они не получат никаких сообщений об ошибках, так как это покажет существование их учетной записи, но почта не будет быть отправленным либо.
Атрибуты:
- template_name : Полное имя шаблона, который будет использоваться для отображения формы сброса пароля. По умолчанию, registration/password_reset_form.html если не указан.
- form_class : Форма, которая будет использоваться для получения электронной почты пользователя, для которого требуется сбросить пароль. По умолчанию PasswordResetForm .
- email_template_name : Полное имя шаблона, который будет использоваться для создания электронного письма со ссылкой для сброса пароля. По умолчанию, registration/password_reset_email.html если не указан.
- subject_template_name : Полное имя шаблона, который будет использоваться в качестве темы электронного письма со ссылкой для сброса пароля. По умолчанию, registration/password_reset_subject.txt если не указан.
- token_generator : Экземпляр класса для проверки одноразовой ссылки. По умолчанию default_token_generator это экземпляр django.contrib.auth.tokens.PasswordResetTokenGenerator .
- success_url : URL-адрес для перенаправления после успешного запроса сброса пароля. По умолчанию ‘password_reset_done’ .
- from_email : Действующий адрес электронной почты. По умолчанию Django использует расширение DEFAULT_FROM_EMAIL .
- extra_context : Словарь данных контекста, который будет добавлен к данным контекста по умолчанию, передаваемым в шаблон.
- html_email_template_name : Полное имя шаблона, который будет использоваться для создания составного письма text / html со ссылкой для сброса пароля. По умолчанию электронное письмо в формате HTML не отправляется.
- extra_email_context : Словарь контекстных данных, которые будут доступны в шаблоне электронной почты. Его можно использовать для переопределения значений контекста шаблона по умолчанию, перечисленных ниже, например domain .
Контекст шаблона:
- form : Форма (см. form_class Выше) для сброса пароля пользователя.
Контекст шаблона электронного письма:
- email : Псевдоним для user.email
- user : Текущее значение в User соответствии с email полем формы. Только активные пользователи могут сбрасывать свои пароли ( ). User.is_active is True
- site_name : Псевдоним для site.name . Если у вас не установлена платформа сайта, будет установлено значение request.META[‘SERVER_NAME’] . Дополнительные сведения о сайтах см. В разделе « Структура сайтов» .
- domain : Псевдоним для site.domain . Если у вас не установлена платформа сайта, будет установлено значение request.get_host() .
- protocol : http или https
- uid : Первичный ключ пользователя, закодированный в базе 64.
- token : Токен для проверки того, что ссылка для сброса действительна.
Образец registration/password_reset_email.html (шаблон тела письма):
Тот же контекст шаблона используется для шаблона темы. Тема должна быть однострочной простой текстовой строкой.
Имя URL: password_reset_done
Страница, отображаемая после того, как пользователю была отправлена электронная почта со ссылкой для сброса пароля. Это представление вызывается по умолчанию, если для PasswordResetView него не success_url задан явный URL.
Если указанный адрес электронной почты не существует в системе, пользователь неактивен или имеет непригодный для использования пароль, пользователь все равно будет перенаправлен в это представление, но электронное письмо не будет отправлено.
Атрибуты:
- template_name : Полное имя используемого шаблона. По умолчанию, registration/password_reset_done.html если не указан.
- extra_context : Словарь данных контекста, который будет добавлен к данным контекста по умолчанию, передаваемым в шаблон.
Имя URL: password_reset_confirm
Представляет форму для ввода нового пароля.
Аргументы ключевого слова из URL:
- uidb64 : Идентификатор пользователя в кодировке base 64.
- token : Токен для проверки правильности пароля.
Атрибуты:
- template_name : Полное имя шаблона для отображения окна подтверждения пароля. Значение по умолчанию registration/password_reset_confirm.html .
- token_generator : Экземпляр класса для проверки пароля. По умолчанию default_token_generator это экземпляр django.contrib.auth.tokens.PasswordResetTokenGenerator .
- post_reset_login : Логическое значение, указывающее, следует ли автоматически аутентифицировать пользователя после успешного сброса пароля. По умолчанию False .
- post_reset_login_backend : Пунктирный путь к бэкэнду аутентификации, который будет использоваться при аутентификации пользователя, если post_reset_login есть True . Требуется только в том случае, если у вас AUTHENTICATION_BACKENDS настроено несколько . По умолчанию None .
- form_class : Форма, которая будет использоваться для установки пароля. По умолчанию SetPasswordForm .
- success_url : URL для перенаправления после сброса пароля. По умолчанию ‘password_reset_complete’ .
- extra_context : Словарь данных контекста, который будет добавлен к данным контекста по умолчанию, передаваемым в шаблон.
- reset_url_token : Параметр токена отображается как компонент URL-адресов для сброса пароля. По умолчанию ‘set-password’ .
Контекст шаблона:
- form : Форма (см. form_class Выше) для установки пароля нового пользователя.
- validlink : Boolean, Истина, если ссылка (комбинация uidb64 и token ) действующая или еще не использовалась.
Имя URL: password_reset_complete
Представляет представление, информирующее пользователя об успешном изменении пароля.
Атрибуты:
- template_name : Полное имя шаблона для отображения представления. По умолчанию registration/password_reset_complete.html .
- extra_context : Словарь данных контекста, который будет добавлен к данным контекста по умолчанию, передаваемым в шаблон.
Вспомогательные функции ¶
Перенаправляет на страницу входа, а затем обратно на другой URL-адрес после успешного входа.
Обязательные аргументы:
- next : URL-адрес для перенаправления после успешного входа в систему.
Необязательные аргументы:
- login_url : URL-адрес страницы входа, на которую выполняется перенаправление. По умолчанию, settings.LOGIN_URL если не указан.
- redirect_field_name : Имя GET поля, содержащего URL-адрес для перенаправления после выхода из системы. Переопределяет, next если данный GET параметр передан.
Встроенные формы ¶
Если вы не хотите использовать встроенные представления, но хотите, чтобы вам не приходилось писать формы для этой функции, система аутентификации предоставляет несколько встроенных форм, расположенных в django.contrib.auth.forms :
Встроенные формы аутентификации делают определенные предположения о пользовательской модели, с которой они работают. Если вы используете настраиваемую модель пользователя , может потребоваться определение ваших собственных форм для системы аутентификации. Дополнительные сведения см. В документации по использованию встроенных форм проверки подлинности с настраиваемыми моделями пользователей .
Форма, используемая в интерфейсе администратора для изменения пароля пользователя.
Принимает в user качестве первого позиционного аргумента.
Форма для входа пользователя в систему.
Принимает в request качестве своего первого позиционного аргумента, который хранится в экземпляре формы для использования подклассами.
По умолчанию AuthenticationForm отклоняет пользователей, для которых установлен is_active флаг False . Вы можете переопределить это поведение с помощью настраиваемой политики, чтобы определить, какие пользователи могут войти в систему. Сделайте это с помощью настраиваемой формы, которая подклассирует AuthenticationForm и переопределяет confirm_login_allowed() метод. Этот метод должен вызывать, ValidationError если данный пользователь не может войти в систему.
Например, чтобы разрешить всем пользователям входить в систему независимо от «активного» статуса:
(В этом случае вам также необходимо использовать серверную часть аутентификации, которая разрешает неактивным пользователям, например AllowAllUsersModelBackend .)
Или разрешить вход только некоторым активным пользователям:
Форма, позволяющая пользователю изменить свой пароль.
Форма для создания и отправки по электронной почте одноразовой ссылки для сброса пароля пользователя.
send_mail ( имя_имя_темплита , имя_элемента_почты , контекст , адрес_отправки , адрес_почты , html_email_template_name = Нет ) ¶
Использует аргументы для отправки EmailMultiAlternatives . Можно переопределить, чтобы настроить способ отправки электронной почты пользователю.
- subject_template_name — шаблон для темы.
- email_template_name — шаблон тела письма.
- контекст — контекст , передаваемый в subject_template , email_template и html_email_template (если это не None ).
- from_email — адрес электронной почты отправителя.
- to_email — адрес электронной почты запрашивающего.
- html_email_template_name — шаблон для тела HTML; по умолчанию None , в этом случае отправляется электронное письмо в виде простого текста.
По умолчанию save() заполняет те context же переменные, которые PasswordResetView передаются в его контекст электронной почты.
Форма, позволяющая пользователю изменить свой пароль, не вводя старый пароль.
Форма, используемая в интерфейсе администратора для изменения информации и разрешений пользователя.
A ModelForm для создания нового пользователя.
Он имеет три поля: username (из пользовательской модели) password1 , и password2 . Он проверяет это password1 и password2 соответствует, проверяет пароль с помощью validate_password() и устанавливает пароль пользователя с помощью set_password() .
Данные для аутентификации в шаблонах ¶
Текущий вошедший в систему пользователь и его разрешения становятся доступными в контексте шаблона при использовании RequestContext .
Технически эти переменные становятся доступными в контексте шаблона только в том случае, если вы его используете RequestContext и ‘django.contrib.auth.context_processors.auth’ контекстный процессор включен. Он находится в сгенерированном по умолчанию файле настроек. Дополнительные сведения см. В документации RequestContext .
Пользователи ¶
При рендеринге шаблона RequestContext текущий авторизованный пользователь, либо User экземпляр, либо AnonymousUser экземпляр, сохраняется в переменной шаблона : << user >>
Эта переменная контекста шаблона недоступна, если RequestContext не используется.
Разрешения ¶
Права текущего пользователя, вошедшего в систему, хранятся в переменной шаблона . Это экземпляр , который представляет собой удобный для шаблонов прокси-сервер разрешений. << perms >> django.contrib.auth.context_processors.PermWrapper
Оценка поиска по одному атрибуту как логического является прокси для . Например, чтобы проверить, есть ли у вошедшего в систему пользователя какие-либо разрешения в приложении: << perms >> User.has_module_perms() foo
Оценка поиска двухуровневого атрибута как логического является прокси для User.has_perm() . Например, чтобы проверить, есть ли у вошедшего в систему пользователя разрешение foo.add_vote :
Вот более полный пример проверки разрешений в шаблоне:
Можно также посмотреть разрешения по операторам. Например:
Управление пользователями в админке ¶
Когда у вас есть и то, django.contrib.admin и другое django.contrib.auth , администратор предоставляет удобный способ просмотра и управления пользователями, группами и разрешениями. Пользователи могут быть созданы и удалены, как любая модель Django. Можно создавать группы и назначать разрешения пользователям или группам. Также сохраняется и отображается журнал изменений моделей, внесенных пользователем в админку.
Создание пользователей ¶
Вы должны увидеть ссылку на «Пользователи» в разделе «Auth» на главной странице индекса администратора. Страница администратора «Добавить пользователя» отличается от стандартных страниц администрирования тем, что требует от вас выбора имени пользователя и пароля, прежде чем вы сможете редактировать остальные поля пользователя.
Также обратите внимание: если вы хотите, чтобы учетная запись пользователя могла создавать пользователей с помощью сайта администратора Django, вам необходимо предоставить им разрешение на добавление и изменение пользователей (например, разрешения «Добавить пользователя» и «Изменить пользователя»). . Если у учетной записи есть разрешение на добавление пользователей, но не на их изменение, эта учетная запись не сможет добавлять пользователей. Почему? Потому что, если у вас есть разрешение на добавление пользователей, у вас есть возможность создавать суперпользователей, которые, в свою очередь, могут изменять других пользователей. Таким образом, Django требует добавления и изменения разрешений в качестве небольшой меры безопасности.
Обдумайте, как вы позволяете пользователям управлять разрешениями. Если вы дадите пользователю, не являющемуся суперпользователем, возможность редактировать пользователей, это будет в конечном итоге то же самое, что дать им статус суперпользователя, потому что они смогут повышать права пользователей, включая самих себя!
Смена паролей ¶
Пароли пользователей не отображаются в админке (и не хранятся в базе данных), но отображаются сведения о хранилище паролей . В отображении этой информации есть ссылка на форму изменения пароля, которая позволяет администраторам изменять пароли пользователей.
Как удалить суперпользователя в django
Now that we’ve created models for the LocalLibrary website, we’ll use the Django Admin site to add some «real» book data. First we’ll show you how to register the models with the admin site, then we’ll show you how to login and create some data. At the end of the article we will show some of the ways you can further improve the presentation of the Admin site.
| Prerequisites: | First complete: Django Tutorial Part 3: Using models. |
|---|---|
| Objective: | To understand the benefits and limitations of the Django admin site, and use it to create some records for our models. |
Overview
The Django admin application can use your models to automatically build a site area that you can use to create, view, update, and delete records. This can save you a lot of time during development, making it very easy to test your models and get a feel for whether you have the right data. The admin application can also be useful for managing data in production, depending on the type of website. The Django project recommends it only for internal data management (i.e. just for use by admins, or people internal to your organization), as the model-centric approach is not necessarily the best possible interface for all users, and exposes a lot of unnecessary detail about the models.
All the configuration required to include the admin application in your website was done automatically when you created the skeleton project (for information about actual dependencies needed, see the Django docs here). As a result, all you must do to add your models to the admin application is to register them. At the end of this article we’ll provide a brief demonstration of how you might further configure the admin area to better display our model data.
After registering the models we’ll show how to create a new «superuser», login to the site, and create some books, authors, book instances, and genres. These will be useful for testing the views and templates we’ll start creating in the next tutorial.
Registering models
First, open admin.py in the catalog application (/locallibrary/catalog/admin.py). It currently looks like this — note that it already imports django.contrib.admin :
Register the models by copying the following text into the bottom of the file. This code imports the models and then calls admin.site.register to register each of them.
Note: If you accepted the challenge to create a model to represent the natural language of a book (see the models tutorial article), import and register it too!
This is the simplest way of registering a model, or models, with the site. The admin site is highly customizable, and we’ll talk more about the other ways of registering your models further down.
Creating a superuser
In order to log into the admin site, we need a user account with Staff status enabled. In order to view and create records we also need this user to have permissions to manage all our objects. You can create a «superuser» account that has full access to the site and all needed permissions using manage.py.
Call the following command, in the same directory as manage.py, to create the superuser. You will be prompted to enter a username, email address, and strong password.
Once this command completes a new superuser will have been added to the database. Now restart the development server so we can test the login:
Logging in and using the site
To login to the site, open the /admin URL (e.g. http://127.0.0.1:8000/admin ) and enter your new superuser userid and password credentials (you’ll be redirected to the login page, and then back to the /admin URL after you’ve entered your details).
This part of the site displays all our models, grouped by installed application. You can click on a model name to go to a screen that lists all its associated records, and you can further click on those records to edit them. You can also directly click the Add link next to each model to start creating a record of that type.

Click on the Add link to the right of Books to create a new book (this will display a dialog much like the one below). Note how the titles of each field, the type of widget used, and the help_text (if any) match the values you specified in the model.
Enter values for the fields. You can create new authors or genres by pressing the + button next to the respective fields (or select existing values from the lists if you’ve already created them). When you’re done you can press SAVE, Save and add another, or Save and continue editing to save the record.

Note: At this point we’d like you to spend some time adding a few books, authors, and genres (e.g. Fantasy) to your application. Make sure that each author and genre includes a couple of different books (this will make your list and detail views more interesting when we implement them later on in the article series).
When you’ve finished adding books, click on the Home link in the top bookmark to be taken back to the main admin page. Then click on the Books link to display the current list of books (or on one of the other links to see other model lists). Now that you’ve added a few books, the list might look similar to the screenshot below. The title of each book is displayed; this is the value returned in the Book model’s __str__() method that we specified in the last article.

From this list you can delete books by selecting the checkbox next to the book you don’t want, selecting the delete… action from the Action drop-down list, and then pressing the Go button. You can also add new books by pressing the ADD BOOK button.
You can edit a book by selecting its name in the link. The edit page for a book, shown below, is almost identical to the «Add» page. The main differences are the page title (Change book) and the addition of Delete, HISTORY and VIEW ON SITE buttons (this last button appears because we defined the get_absolute_url() method in our model).

Now navigate back to the Home page (using the Home link in the breadcrumb trail) and then view the Author and Genre lists — you should already have quite a few created from when you added the new books, but feel free to add some more.
What you won’t have is any Book Instances, because these are not created from Books (although you can create a Book from a BookInstance — this is the nature of the ForeignKey field). Navigate back to the Home page and press the associated Add button to display the Add book instance screen below. Note the large, globally unique Id, which can be used to separately identify a single copy of a book in the library.

Create a number of these records for each of your books. Set the status as Available for at least some records and On loan for others. If the status is not Available, then also set a future Due back date.
That’s it! You’ve now learned how to set up and use the administration site. You’ve also created records for Book , BookInstance , Genre , and Author that we’ll be able to use once we create our own views and templates.
Advanced configuration
Django does a pretty good job of creating a basic admin site using the information from the registered models:
- Each model has a list of individual records, identified by the string created with the model’s __str__() method, and linked to detail views/forms for editing. By default, this view has an action menu at the top that you can use to perform bulk delete operations on records.
- The model detail record forms for editing and adding records contain all the fields in the model, laid out vertically in their declaration order.
You can further customize the interface to make it even easier to use. Some of the things you can do are:
- List views:
- Add additional fields/information displayed for each record.
- Add filters to select which records are listed, based on date or some other selection value (e.g. Book loan status).
- Add additional options to the actions menu in list views and choose where this menu is displayed on the form.
- Choose which fields to display (or exclude), along with their order, grouping, whether they are editable, the widget used, orientation etc.
- Add related fields to a record to allow inline editing (e.g. add the ability to add and edit book records while you’re creating their author record).
In this section we’re going to look at a few changes that will improve the interface for our LocalLibrary, including adding more information to Book and Author model lists, and improving the layout of their edit views. We won’t change the Language and Genre model presentation because they only have one field each, so there is no real benefit in doing so!
You can find a complete reference of all the admin site customization choices in The Django Admin site (Django Docs).
Register a ModelAdmin class
To change how a model is displayed in the admin interface you define a ModelAdmin class (which describes the layout) and register it with the model.
Let’s start with the Author model. Open admin.py in the catalog application (/locallibrary/catalog/admin.py). Comment out your original registration (prefix it with a #) for the Author model:
Now add a new AuthorAdmin and registration as shown below.
Now we’ll add ModelAdmin classes for Book , and BookInstance . We again need to comment out the original registrations:
Now to create and register the new models; for the purpose of this demonstration, we’ll instead use the @register decorator to register the models (this does exactly the same thing as the admin.site.register() syntax):
Currently all of our admin classes are empty (see pass ) so the admin behavior will be unchanged! We can now extend these to define our model-specific admin behavior.
Configure list views
The LocalLibrary currently lists all authors using the object name generated from the model __str__() method. This is fine when you only have a few authors, but once you have many you may end up having duplicates. To differentiate them, or just because you want to show more interesting information about each author, you can use list_display to add additional fields to the view.
Replace your AuthorAdmin class with the code below. The field names to be displayed in the list are declared in a tuple in the required order, as shown (these are the same names as specified in your original model).
Now navigate to the author list in your website. The fields above should now be displayed, like so:

For our Book model we’ll additionally display the author and genre . The author is a ForeignKey field (one-to-many) relationship, and so will be represented by the __str__() value for the associated record. Replace the BookAdmin class with the version below.
Unfortunately we can’t directly specify the genre field in list_display because it is a ManyToManyField (Django prevents this because there would be a large database access «cost» in doing so). Instead we’ll define a display_genre function to get the information as a string (this is the function we’ve called above; we’ll define it below).
Note: Getting the genre may not be a good idea here, because of the «cost» of the database operation. We’re showing you how because calling functions in your models can be very useful for other reasons — for example to add a Delete link next to every item in the list.
Add the following code into your Book model (models.py). This creates a string from the first three values of the genre field (if they exist) and creates a short_description that can be used in the admin site for this method.
After saving the model and updated admin, open your website and go to the Books list page; you should see a book list like the one below:

The Genre model (and the Language model, if you defined one) both have a single field, so there is no point creating an additional model for them to display additional fields.
Note: It is worth updating the BookInstance model list to show at least the status and the expected return date. We’ve added that as a challenge at the end of this article!
Add list filters
Once you’ve got a lot of items in a list, it can be useful to be able to filter which items are displayed. This is done by listing fields in the list_filter attribute. Replace your current BookInstanceAdmin class with the code fragment below.
The list view will now include a filter box to the right. Note how you can choose dates and status to filter the values:

Organize detail view layout
By default, the detail views lay out all fields vertically, in their order of declaration in the model. You can change the order of declaration, which fields are displayed (or excluded), whether sections are used to organize the information, whether fields are displayed horizontally or vertically, and even what edit widgets are used in the admin forms.
Note: The LocalLibrary models are relatively simple so there isn’t a huge need for us to change the layout; we’ll make some changes anyway however, just to show you how.
Controlling which fields are displayed and laid out
Update your AuthorAdmin class to add the fields line, as shown below:
The fields attribute lists just those fields that are to be displayed on the form, in order. Fields are displayed vertically by default, but will display horizontally if you further group them in a tuple (as shown in the «date» fields above).
In your website go to the author detail view — it should now appear as shown below:

Note: You can also use the exclude attribute to declare a list of attributes to be excluded from the form (all other attributes in the model will be displayed).
Sectioning the detail view
You can add «sections» to group related model information within the detail form, using the fieldsets attribute.
In the BookInstance model we have information related to what the book is (i.e. name , imprint , and id ) and when it will be available ( status , due_back ). We can add these to our BookInstanceAdmin class as shown below, using the fieldsets property.
Each section has its own title (or None , if you don’t want a title) and an associated tuple of fields in a dictionary — the format is complicated to describe, but fairly easy to understand if you look at the code fragment immediately above.
Now navigate to a book instance view in your website; the form should appear as shown below:

Inline editing of associated records
Sometimes it can make sense to be able to add associated records at the same time. For example, it may make sense to have both the book information and information about the specific copies you’ve got on the same detail page.
You can do this by declaring inlines, of type TabularInline (horizontal layout) or StackedInline (vertical layout, just like the default model layout). You can add the BookInstance information inline to our Book detail by specifying inlines in your BookAdmin :
Now navigate to a view for a Book in your website — at the bottom you should now see the book instances relating to this book (immediately below the book’s genre fields):

In this case all we’ve done is declare our tabular inline class, which just adds all fields from the inlined model. You can specify all sorts of additional information for the layout, including the fields to display, their order, whether they are read only or not, etc. (see TabularInline for more information).
Note: There are some painful limits in this functionality! In the screenshot above we have three existing book instances, followed by three placeholders for new book instances (which look very similar!). It would be better to have NO spare book instances by default and just add them with the Add another Book instance link, or to be able to just list the BookInstance s as non-readable links from here. The first option can be done by setting the extra attribute to 0 in BooksInstanceInline model, try it by yourself.
Challenge yourself
We’ve learned a lot in this section, so now it is time for you to try a few things.
- For the BookInstance list view, add code to display the book, status, due back date, and id (rather than the default __str__() text).
- Add an inline listing of Book items to the Author detail view using the same approach as we did for Book / BookInstance .
Summary
That’s it! You’ve now learned how to set up the administration site in both its simplest and improved form, how to create a superuser, and how to navigate the admin site and view, delete, and update records. Along the way you’ve created a bunch of Books, BookInstances, Genres, and Authors that we’ll be able to list and display once we create our own view and templates.
Django delete superuser
This may be a duplicate, but I couldn’t find the question anywhere, so I’ll go ahead and ask:
Is there a simple way to delete a superuser from the terminal, perhaps analogous to Django’s createsuperuser command?

7 Answers 7
There’s no built in command but you can easily do this from the shell:
An answer for people who did not use Django’s User model instead substituted a Django custom user model.
Now to delete a registered SUPERUSER in our system:
No need to delete superuser. just create another superuser. You can create another superuser with same name as the previous one. I have forgotten the password of the superuser so I create another superuser with the same name as previously.
django-admin and manage.py ¶
django-admin is Django’s command-line utility for administrative tasks. This document outlines all it can do.
In addition, manage.py is automatically created in each Django project. It does the same thing as django-admin but also sets the DJANGO_SETTINGS_MODULE environment variable so that it points to your project’s settings.py file.
The django-admin script should be on your system path if you installed Django via pip . If it’s not in your path, ensure you have your virtual environment activated.
Generally, when working on a single Django project, it’s easier to use manage.py than django-admin . If you need to switch between multiple Django settings files, use django-admin with DJANGO_SETTINGS_MODULE or the —settings command line option.
The command-line examples throughout this document use django-admin to be consistent, but any example can use manage.py or python -m django just as well.
Usage¶
command should be one of the commands listed in this document. options , which is optional, should be zero or more of the options available for the given command.
Getting runtime help¶
Run django-admin help to display usage information and a list of the commands provided by each application.
Run django-admin help —commands to display a list of all available commands.
Run django-admin help <command> to display a description of the given command and a list of its available options.
App names¶
Many commands take a list of “app names.” An “app name” is the basename of the package containing your models. For example, if your INSTALLED_APPS contains the string ‘mysite.blog’ , the app name is blog .
Determining the version¶
Run django-admin version to display the current Django version.
The output follows the schema described in PEP 440:
Displaying debug output¶
Use —verbosity , where it is supported, to specify the amount of notification and debug information that django-admin prints to the console.
Available commands¶
check ¶
Uses the system check framework to inspect the entire Django project for common problems.
By default, all apps will be checked. You can check a subset of apps by providing a list of app labels as arguments:
The system check framework performs many different types of checks that are categorized with tags . You can use these tags to restrict the checks performed to just those in a particular category. For example, to perform only models and compatibility checks, run:
Specifies the database to run checks requiring database access:
By default, these checks will not be run.
Lists all available tags.
Activates some additional checks that are only relevant in a deployment setting.
You can use this option in your local development environment, but since your local development settings module may not have many of your production settings, you will probably want to point the check command at a different settings module, either by setting the DJANGO_SETTINGS_MODULE environment variable, or by passing the —settings option:
Or you could run it directly on a production or staging deployment to verify that the correct settings are in use (omitting —settings ). You could even make it part of your integration test suite.
Specifies the message level that will cause the command to exit with a non-zero status. Default is ERROR .
compilemessages ¶
Compiles .po files created by makemessages to .mo files for use with the built-in gettext support. See Internationalization and localization .
—locale LOCALE , -l LOCALE ¶
Specifies the locale(s) to process. If not provided, all locales are processed.
—exclude EXCLUDE , -x EXCLUDE ¶
Specifies the locale(s) to exclude from processing. If not provided, no locales are excluded.
Includes fuzzy translations into compiled files.
Ignores directories matching the given glob -style pattern. Use multiple times to ignore more.
createcachetable ¶
Creates the cache tables for use with the database cache backend using the information from your settings file. See Django’s cache framework for more information.
Specifies the database in which the cache table(s) will be created. Defaults to default .
Prints the SQL that would be run without actually running it, so you can customize it or use the migrations framework.
dbshell ¶
Runs the command-line client for the database engine specified in your ENGINE setting, with the connection parameters specified in your USER , PASSWORD , etc., settings.
- For PostgreSQL, this runs the psql command-line client.
- For MySQL, this runs the mysql command-line client.
- For SQLite, this runs the sqlite3 command-line client.
- For Oracle, this runs the sqlplus command-line client.
This command assumes the programs are on your PATH so that a call to the program name ( psql , mysql , sqlite3 , sqlplus ) will find the program in the right place. There’s no way to specify the location of the program manually.
Specifies the database onto which to open a shell. Defaults to default .
Any arguments following a — divider will be passed on to the underlying command-line client. For example, with PostgreSQL you can use the psql command’s -c flag to execute a raw SQL query directly:
On MySQL/MariaDB, you can do this with the mysql command’s -e flag:
Be aware that not all options set in the OPTIONS part of your database configuration in DATABASES are passed to the command-line client, e.g. ‘isolation_level’ .
diffsettings ¶
Displays differences between the current settings file and Django’s default settings (or another settings file specified by —default ).
Settings that don’t appear in the defaults are followed by «###» . For example, the default settings don’t define ROOT_URLCONF , so ROOT_URLCONF is followed by «###» in the output of diffsettings .
Displays all settings, even if they have Django’s default value. Such settings are prefixed by «###» .
The settings module to compare the current settings against. Leave empty to compare against Django’s default settings.
Specifies the output format. Available values are hash and unified . hash is the default mode that displays the output that’s described above. unified displays the output similar to diff -u . Default settings are prefixed with a minus sign, followed by the changed setting prefixed with a plus sign.
dumpdata ¶
Outputs to standard output all data in the database associated with the named application(s).
If no application name is provided, all installed applications will be dumped.
The output of dumpdata can be used as input for loaddata .
Note that dumpdata uses the default manager on the model for selecting the records to dump. If you’re using a custom manager as the default manager and it filters some of the available records, not all of the objects will be dumped.
Uses Django’s base manager, dumping records which might otherwise be filtered or modified by a custom manager.
Specifies the serialization format of the output. Defaults to JSON. Supported formats are listed in Serialization formats .
Specifies the number of indentation spaces to use in the output. Defaults to None which displays all data on single line.
—exclude EXCLUDE , -e EXCLUDE ¶
Prevents specific applications or models (specified in the form of app_label.ModelName ) from being dumped. If you specify a model name, then only that model will be excluded, rather than the entire application. You can also mix application names and model names.
If you want to exclude multiple applications, pass —exclude more than once:
Specifies the database from which data will be dumped. Defaults to default .
Uses the natural_key() model method to serialize any foreign key and many-to-many relationship to objects of the type that defines the method. If you’re dumping contrib.auth Permission objects or contrib.contenttypes ContentType objects, you should probably use this flag. See the natural keys documentation for more details on this and the next option.
Omits the primary key in the serialized data of this object since it can be calculated during deserialization.
Outputs only the objects specified by a comma separated list of primary keys. This is only available when dumping one model. By default, all the records of the model are output.
—output OUTPUT , -o OUTPUT ¶
Specifies a file to write the serialized data to. By default, the data goes to standard output.
When this option is set and —verbosity is greater than 0 (the default), a progress bar is shown in the terminal.
Fixtures compression¶
The output file can be compressed with one of the bz2 , gz , lzma , or xz formats by ending the filename with the corresponding extension. For example, to output the data as a compressed JSON file:
flush ¶
Removes all data from the database and re-executes any post-synchronization handlers. The table of which migrations have been applied is not cleared.
If you would rather start from an empty database and rerun all migrations, you should drop and recreate the database and then run migrate instead.
Suppresses all user prompts.
Specifies the database to flush. Defaults to default .
inspectdb ¶
Introspects the database tables in the database pointed-to by the NAME setting and outputs a Django model module (a models.py file) to standard output.
You may choose what tables or views to inspect by passing their names as arguments. If no arguments are provided, models are created for views only if the —include-views option is used. Models for partition tables are created on PostgreSQL if the —include-partitions option is used.
Use this if you have a legacy database with which you’d like to use Django. The script will inspect the database and create a model for each table within it.
As you might expect, the created models will have an attribute for every field in the table. Note that inspectdb has a few special cases in its field-name output:
- If inspectdb cannot map a column’s type to a model field type, it’ll use TextField and will insert the Python comment ‘This field type is a guess.’ next to the field in the generated model. The recognized fields may depend on apps listed in INSTALLED_APPS . For example, django.contrib.postgres adds recognition for several PostgreSQL-specific field types.
- If the database column name is a Python reserved word (such as ‘pass’ , ‘class’ or ‘for’ ), inspectdb will append ‘_field’ to the attribute name. For example, if a table has a column ‘for’ , the generated model will have a field ‘for_field’ , with the db_column attribute set to ‘for’ . inspectdb will insert the Python comment ‘Field renamed because it was a Python reserved word.’ next to the field.
This feature is meant as a shortcut, not as definitive model generation. After you run it, you’ll want to look over the generated models yourself to make customizations. In particular, you’ll need to rearrange models’ order, so that models that refer to other models are ordered properly.
Django doesn’t create database defaults when a default is specified on a model field. Similarly, database defaults aren’t translated to model field defaults or detected in any fashion by inspectdb .
By default, inspectdb creates unmanaged models. That is, managed = False in the model’s Meta class tells Django not to manage each table’s creation, modification, and deletion. If you do want to allow Django to manage the table’s lifecycle, you’ll need to change the managed option to True (or remove it because True is its default value).
Database-specific notes¶
Oracle¶
- Models are created for materialized views if —include-views is used.
PostgreSQL¶
- Models are created for foreign tables.
- Models are created for materialized views if —include-views is used.
- Models are created for partition tables if —include-partitions is used.
Specifies the database to introspect. Defaults to default .
If this option is provided, models are also created for partitions.
Only support for PostgreSQL is implemented.
If this option is provided, models are also created for database views.
loaddata ¶
Searches for and loads the contents of the named fixture into the database.
Specifies the database into which the data will be loaded. Defaults to default .
Ignores fields and models that may have been removed since the fixture was originally generated.
Specifies a single app to look for fixtures in rather than looking in all apps.
Specifies the serialization format (e.g., json or xml ) for fixtures read from stdin .
—exclude EXCLUDE , -e EXCLUDE ¶
Excludes loading the fixtures from the given applications and/or models (in the form of app_label or app_label.ModelName ). Use the option multiple times to exclude more than one app or model.
What’s a “fixture”?¶
A fixture is a collection of files that contain the serialized contents of the database. Each fixture has a unique name, and the files that comprise the fixture can be distributed over multiple directories, in multiple applications.
Django will search in three locations for fixtures:
- In the fixtures directory of every installed application
- In any directory named in the FIXTURE_DIRS setting
- In the literal path named by the fixture
Django will load any and all fixtures it finds in these locations that match the provided fixture names.
If the named fixture has a file extension, only fixtures of that type will be loaded. For example:
would only load JSON fixtures called mydata . The fixture extension must correspond to the registered name of a serializer (e.g., json or xml ).
If you omit the extensions, Django will search all available fixture types for a matching fixture. For example:
would look for any fixture of any fixture type called mydata . If a fixture directory contained mydata.json , that fixture would be loaded as a JSON fixture.
The fixtures that are named can include directory components. These directories will be included in the search path. For example:
would search <app_label>/fixtures/foo/bar/mydata.json for each installed application, <dirname>/foo/bar/mydata.json for each directory in FIXTURE_DIRS , and the literal path foo/bar/mydata.json .
When fixture files are processed, the data is saved to the database as is. Model defined save() methods are not called, and any pre_save or post_save signals will be called with raw=True since the instance only contains attributes that are local to the model. You may, for example, want to disable handlers that access related fields that aren’t present during fixture loading and would otherwise raise an exception:
You could also write a decorator to encapsulate this logic:
Just be aware that this logic will disable the signals whenever fixtures are deserialized, not just during loaddata .
Note that the order in which fixture files are processed is undefined. However, all fixture data is installed as a single transaction, so data in one fixture can reference data in another fixture. If the database backend supports row-level constraints, these constraints will be checked at the end of the transaction.
The dumpdata command can be used to generate input for loaddata .
Compressed fixtures¶
Fixtures may be compressed in zip , gz , bz2 , lzma , or xz format. For example:
would look for any of mydata.json , mydata.json.zip , mydata.json.gz , mydata.json.bz2 , mydata.json.lzma , or mydata.json.xz . The first file contained within a compressed archive is used.
Note that if two fixtures with the same name but different fixture type are discovered (for example, if mydata.json and mydata.xml.gz were found in the same fixture directory), fixture installation will be aborted, and any data installed in the call to loaddata will be removed from the database.
MySQL with MyISAM and fixtures
The MyISAM storage engine of MySQL doesn’t support transactions or constraints, so if you use MyISAM, you won’t get validation of fixture data, or a rollback if multiple transaction files are found.
Database-specific fixtures¶
If you’re in a multi-database setup, you might have fixture data that you want to load onto one database, but not onto another. In this situation, you can add a database identifier into the names of your fixtures.
For example, if your DATABASES setting has a ‘users’ database defined, name the fixture mydata.users.json or mydata.users.json.gz and the fixture will only be loaded when you specify you want to load data into the users database.
Loading fixtures from stdin ¶
You can use a dash as the fixture name to load input from sys.stdin . For example:
When reading from stdin , the —format option is required to specify the serialization format of the input (e.g., json or xml ).
Loading from stdin is useful with standard input and output redirections. For example:
makemessages ¶
Runs over the entire source tree of the current directory and pulls out all strings marked for translation. It creates (or updates) a message file in the conf/locale (in the Django tree) or locale (for project and application) directory. After making changes to the messages files you need to compile them with compilemessages for use with the builtin gettext support. See the i18n documentation for details.
This command doesn’t require configured settings. However, when settings aren’t configured, the command can’t ignore the MEDIA_ROOT and STATIC_ROOT directories or include LOCALE_PATHS .
Updates the message files for all available languages.
—extension EXTENSIONS , -e EXTENSIONS ¶
Specifies a list of file extensions to examine (default: html , txt , py or js if —domain is js ).
Separate multiple extensions with commas or use -e or —extension multiple times:
Specifies the locale(s) to process.
—exclude EXCLUDE , -x EXCLUDE ¶
Specifies the locale(s) to exclude from processing. If not provided, no locales are excluded.
Specifies the domain of the messages files. Supported options are:
- django for all *.py , *.html and *.txt files (default)
- djangojs for *.js files
Follows symlinks to directories when looking for new translation strings.
Ignores files or directories matching the given glob -style pattern. Use multiple times to ignore more.
Disables the default values of —ignore .
Disables breaking long message lines into several lines in language files.
Suppresses writing ‘ #: filename:line ’ comment lines in language files. Using this option makes it harder for technically skilled translators to understand each message’s context.
Controls #: filename:line comment lines in language files. If the option is:
- full (the default if not given): the lines include both file name and line number.
- file : the line number is omitted.
- never : the lines are suppressed (same as —no-location ).
Requires gettext 0.19 or newer.
Prevents deleting the temporary .pot files generated before creating the .po file. This is useful for debugging errors which may prevent the final language files from being created.
See Customizing the makemessages command for instructions on how to customize the keywords that makemessages passes to xgettext .
makemigrations ¶
Creates new migrations based on the changes detected to your models. Migrations, their relationship with apps and more are covered in depth in the migrations documentation .
Providing one or more app names as arguments will limit the migrations created to the app(s) specified and any dependencies needed (the table at the other end of a ForeignKey , for example).
To add migrations to an app that doesn’t have a migrations directory, run makemigrations with the app’s app_label .
Suppresses all user prompts. If a suppressed prompt cannot be resolved automatically, the command will exit with error code 3.
Outputs an empty migration for the specified apps, for manual editing. This is for advanced users and should not be used unless you are familiar with the migration format, migration operations, and the dependencies between your migrations.
Shows what migrations would be made without actually writing any migrations files to disk. Using this option along with —verbosity 3 will also show the complete migrations files that would be written.
Enables fixing of migration conflicts.
Allows naming the generated migration(s) instead of using a generated name. The name must be a valid Python identifier .
Generate migration files without Django version and timestamp header.
Makes makemigrations exit with a non-zero status when model changes without migrations are detected.
Diverts log output and input prompts to stderr , writing only paths of generated migration files to stdout .
migrate ¶
Synchronizes the database state with the current set of models and migrations. Migrations, their relationship with apps and more are covered in depth in the migrations documentation .
The behavior of this command changes depending on the arguments provided:
- No arguments: All apps have all of their migrations run.
- <app_label> : The specified app has its migrations run, up to the most recent migration. This may involve running other apps’ migrations too, due to dependencies.
- <app_label> <migrationname> : Brings the database schema to a state where the named migration is applied, but no later migrations in the same app are applied. This may involve unapplying migrations if you have previously migrated past the named migration. You can use a prefix of the migration name, e.g. 0001 , as long as it’s unique for the given app name. Use the name zero to migrate all the way back i.e. to revert all applied migrations for an app.
When unapplying migrations, all dependent migrations will also be unapplied, regardless of <app_label> . You can use —plan to check which migrations will be unapplied.
Specifies the database to migrate. Defaults to default .
Marks the migrations up to the target one (following the rules above) as applied, but without actually running the SQL to change your database schema.
This is intended for advanced users to manipulate the current migration state directly if they’re manually applying changes; be warned that using —fake runs the risk of putting the migration state table into a state where manual recovery will be needed to make migrations run correctly.
Allows Django to skip an app’s initial migration if all database tables with the names of all models created by all CreateModel operations in that migration already exist. This option is intended for use when first running migrations against a database that preexisted the use of migrations. This option does not, however, check for matching database schema beyond matching table names and so is only safe to use if you are confident that your existing schema matches what is recorded in your initial migration.
Shows the migration operations that will be performed for the given migrate command.
Allows creating tables for apps without migrations. While this isn’t recommended, the migrations framework is sometimes too slow on large projects with hundreds of models.
Suppresses all user prompts. An example prompt is asking about removing stale content types.
Makes migrate exit with a non-zero status when unapplied migrations are detected.
Deletes nonexistent migrations from the django_migrations table. This is useful when migration files replaced by a squashed migration have been removed. See Squashing migrations for more details.
optimizemigration ¶
Optimizes the operations for the named migration and overrides the existing file. If the migration contains functions that must be manually copied, the command creates a new migration file suffixed with _optimized that is meant to replace the named migration.
Makes optimizemigration exit with a non-zero status when a migration can be optimized.
runserver ¶
Starts a lightweight development web server on the local machine. By default, the server runs on port 8000 on the IP address 127.0.0.1 . You can pass in an IP address and port number explicitly.
If you run this script as a user with normal privileges (recommended), you might not have access to start a port on a low port number. Low port numbers are reserved for the superuser (root).
This server uses the WSGI application object specified by the WSGI_APPLICATION setting.
DO NOT USE THIS SERVER IN A PRODUCTION SETTING. It has not gone through security audits or performance tests. (And that’s how it’s gonna stay. We’re in the business of making web frameworks, not web servers, so improving this server to be able to handle a production environment is outside the scope of Django.)
The development server automatically reloads Python code for each request, as needed. You don’t need to restart the server for code changes to take effect. However, some actions like adding files don’t trigger a restart, so you’ll have to restart the server in these cases.
If you’re using Linux or MacOS and install both pywatchman and the Watchman service, kernel signals will be used to autoreload the server (rather than polling file modification timestamps each second). This offers better performance on large projects, reduced response time after code changes, more robust change detection, and a reduction in power usage. Django supports pywatchman 1.2.0 and higher.
Large directories with many files may cause performance issues
When using Watchman with a project that includes large non-Python directories like node_modules , it’s advisable to ignore this directory for optimal performance. See the watchman documentation for information on how to do this.
The default timeout of Watchman client is 5 seconds. You can change it by setting the DJANGO_WATCHMAN_TIMEOUT environment variable.
When you start the server, and each time you change Python code while the server is running, the system check framework will check your entire Django project for some common errors (see the check command). If any errors are found, they will be printed to standard output. You can use the —skip-checks option to skip running system checks.
You can run as many concurrent servers as you want, as long as they’re on separate ports by executing django-admin runserver more than once.
Note that the default IP address, 127.0.0.1 , is not accessible from other machines on your network. To make your development server viewable to other machines on the network, use its own IP address (e.g. 192.168.2.1 ) or 0.0.0.0 or :: (with IPv6 enabled).
You can provide an IPv6 address surrounded by brackets (e.g. [200a::1]:8000 ). This will automatically enable IPv6 support.
A hostname containing ASCII-only characters can also be used.
If the staticfiles contrib app is enabled (default in new projects) the runserver command will be overridden with its own runserver command.
Logging of each request and response of the server is sent to the django.server logger.
Disables the auto-reloader. This means any Python code changes you make while the server is running will not take effect if the particular Python modules have already been loaded into memory.
Disables use of threading in the development server. The server is multithreaded by default.
Uses IPv6 for the development server. This changes the default IP address from 127.0.0.1 to ::1 .
Support for the —skip-checks option was added.
Examples of using different ports and addresses¶
Port 8000 on IP address 127.0.0.1 :
Port 8000 on IP address 1.2.3.4 :
Port 7000 on IP address 127.0.0.1 :
Port 7000 on IP address 1.2.3.4 :
Port 8000 on IPv6 address ::1 :
Port 7000 on IPv6 address ::1 :
Port 7000 on IPv6 address 2001:0db8:1234:5678::9 :
Port 8000 on IPv4 address of host localhost :
Port 8000 on IPv6 address of host localhost :
Serving static files with the development server¶
By default, the development server doesn’t serve any static files for your site (such as CSS files, images, things under MEDIA_URL and so forth). If you want to configure Django to serve static media, read How to manage static files (e.g. images, JavaScript, CSS) .
sendtestemail ¶
Sends a test email (to confirm email sending through Django is working) to the recipient(s) specified. For example:
There are a couple of options, and you may use any combination of them together:
Mails the email addresses specified in MANAGERS using mail_managers() .
Mails the email addresses specified in ADMINS using mail_admins() .
shell ¶
Starts the Python interactive interpreter.
Specifies the shell to use. By default, Django will use IPython or bpython if either is installed. If both are installed, specify which one you want like so:
If you have a “rich” shell installed but want to force use of the “plain” Python interpreter, use python as the interface name, like so:
Disables reading the startup script for the “plain” Python interpreter. By default, the script pointed to by the PYTHONSTARTUP environment variable or the
/.pythonrc.py script is read.
—command COMMAND , -c COMMAND ¶
Lets you pass a command as a string to execute it as Django, like so:
You can also pass code in on standard input to execute it. For example:
On Windows, the REPL is output due to implementation limits of select.select() on that platform.
showmigrations ¶
Shows all migrations in a project. You can choose from one of two formats:
Lists all of the apps Django knows about, the migrations available for each app, and whether or not each migration is applied (marked by an [X] next to the migration name). For a —verbosity of 2 and above, the applied datetimes are also shown.
Apps without migrations are also listed, but have (no migrations) printed under them.
This is the default output format.
Shows the migration plan Django will follow to apply migrations. Like —list , applied migrations are marked by an [X] . For a —verbosity of 2 and above, all dependencies of a migration will also be shown.
app_label s arguments limit the output, however, dependencies of provided apps may also be included.
Specifies the database to examine. Defaults to default .
sqlflush ¶
Prints the SQL statements that would be executed for the flush command.
Specifies the database for which to print the SQL. Defaults to default .
sqlmigrate ¶
Prints the SQL for the named migration. This requires an active database connection, which it will use to resolve constraint names; this means you must generate the SQL against a copy of the database you wish to later apply it on.
Note that sqlmigrate doesn’t colorize its output.
Generates the SQL for unapplying the migration. By default, the SQL created is for running the migration in the forwards direction.
Specifies the database for which to generate the SQL. Defaults to default .
sqlsequencereset ¶
Prints the SQL statements for resetting sequences for the given app name(s).
Sequences are indexes used by some database engines to track the next available number for automatically incremented fields.
Use this command to generate SQL which will fix cases where a sequence is out of sync with its automatically incremented field data.
Specifies the database for which to print the SQL. Defaults to default .
squashmigrations ¶
Squashes the migrations for app_label up to and including migration_name down into fewer migrations, if possible. The resulting squashed migrations can live alongside the unsquashed ones safely. For more information, please read Squashing migrations .
When start_migration_name is given, Django will only include migrations starting from and including this migration. This helps to mitigate the squashing limitation of RunPython and django.db.migrations.operations.RunSQL migration operations.
Disables the optimizer when generating a squashed migration. By default, Django will try to optimize the operations in your migrations to reduce the size of the resulting file. Use this option if this process is failing or creating incorrect migrations, though please also file a Django bug report about the behavior, as optimization is meant to be safe.
Suppresses all user prompts.
Sets the name of the squashed migration. When omitted, the name is based on the first and last migration, with _squashed_ in between.
Generate squashed migration file without Django version and timestamp header.
startapp ¶
Creates a Django app directory structure for the given app name in the current directory or the given destination.
By default, the new directory contains a models.py file and other app template files. If only the app name is given, the app directory will be created in the current working directory.
If the optional destination is provided, Django will use that existing directory rather than creating a new one. You can use ‘.’ to denote the current working directory.
Provides the path to a directory with a custom app template file, or a path to an uncompressed archive ( .tar ) or a compressed archive ( .tar.gz , .tar.bz2 , .tar.xz , .tar.lzma , .tgz , .tbz2 , .txz , .tlz , .zip ) containing the app template files.
For example, this would look for an app template in the given directory when creating the myapp app:
Django will also accept URLs ( http , https , ftp ) to compressed archives with the app template files, downloading and extracting them on the fly.
For example, taking advantage of GitHub’s feature to expose repositories as zip files, you can use a URL like:
Specifies which file extensions in the app template should be rendered with the template engine. Defaults to py .
—name FILES , -n FILES ¶
Specifies which files in the app template (in addition to those matching —extension ) should be rendered with the template engine. Defaults to an empty list.
—exclude DIRECTORIES , -x DIRECTORIES ¶
Specifies which directories in the app template should be excluded, in addition to .git and __pycache__ . If this option is not provided, directories named __pycache__ or starting with . will be excluded.
The template context used for all matching files is:
- Any option passed to the startapp command (among the command’s supported options)
- app_name – the app name as passed to the command
- app_directory – the full path of the newly created app
- camel_case_app_name – the app name in camel case format
- docs_version – the version of the documentation: ‘dev’ or ‘1.x’
- django_version – the version of Django, e.g. ‘2.0.3’
When the app template files are rendered with the Django template engine (by default all *.py files), Django will also replace all stray template variables contained. For example, if one of the Python files contains a docstring explaining a particular feature related to template rendering, it might result in an incorrect example.
To work around this problem, you can use the templatetag template tag to “escape” the various parts of the template syntax.
In addition, to allow Python template files that contain Django template language syntax while also preventing packaging systems from trying to byte-compile invalid *.py files, template files ending with .py-tpl will be renamed to .py .
startproject ¶
Creates a Django project directory structure for the given project name in the current directory or the given destination.
By default, the new directory contains manage.py and a project package (containing a settings.py and other files).
If only the project name is given, both the project directory and project package will be named <projectname> and the project directory will be created in the current working directory.
If the optional destination is provided, Django will use that existing directory as the project directory, and create manage.py and the project package within it. Use ‘.’ to denote the current working directory.
Specifies a directory, file path, or URL of a custom project template. See the startapp —template documentation for examples and usage.
—extension EXTENSIONS , -e EXTENSIONS ¶
Specifies which file extensions in the project template should be rendered with the template engine. Defaults to py .
—name FILES , -n FILES ¶
Specifies which files in the project template (in addition to those matching —extension ) should be rendered with the template engine. Defaults to an empty list.
—exclude DIRECTORIES , -x DIRECTORIES ¶
Specifies which directories in the project template should be excluded, in addition to .git and __pycache__ . If this option is not provided, directories named __pycache__ or starting with . will be excluded.
- Any option passed to the startproject command (among the command’s supported options)
- project_name – the project name as passed to the command
- project_directory – the full path of the newly created project
- secret_key – a random key for the SECRET_KEY setting
- docs_version – the version of the documentation: ‘dev’ or ‘1.x’
- django_version – the version of Django, e.g. ‘2.0.3’
Please also see the rendering warning as mentioned for startapp .
Runs tests for all installed apps. See Testing in Django for more information.
Stops running tests and reports the failure immediately after a test fails.
Controls the test runner class that is used to execute tests. This value overrides the value provided by the TEST_RUNNER setting.
Suppresses all user prompts. A typical prompt is a warning about deleting an existing test database.
Test runner options¶
The test command receives options on behalf of the specified —testrunner . These are the options of the default test runner: DiscoverRunner .
Preserves the test database between test runs. This has the advantage of skipping both the create and destroy actions which can greatly decrease the time to run tests, especially those in a large test suite. If the test database does not exist, it will be created on the first run and then preserved for each subsequent run. Unless the MIGRATE test setting is False , any unapplied migrations will also be applied to the test database before running the test suite.
Randomizes the order of tests before running them. This can help detect tests that aren’t properly isolated. The test order generated by this option is a deterministic function of the integer seed given. When no seed is passed, a seed is chosen randomly and printed to the console. To repeat a particular test order, pass a seed. The test orders generated by this option preserve Django’s guarantees on test order . They also keep tests grouped by test case class.
The shuffled orderings also have a special consistency property useful when narrowing down isolation issues. Namely, for a given seed and when running a subset of tests, the new order will be the original shuffling restricted to the smaller set. Similarly, when adding tests while keeping the seed the same, the order of the original tests will be the same in the new order.
Sorts test cases in the opposite execution order. This may help in debugging the side effects of tests that aren’t properly isolated. Grouping by test class is preserved when using this option. This can be used in conjunction with —shuffle to reverse the order for a particular seed.
Sets the DEBUG setting to True prior to running tests. This may help troubleshoot test failures.
Enables SQL logging for failing tests. If —verbosity is 2 , then queries in passing tests are also output.
—parallel [N] ¶ DJANGO_TEST_PROCESSES ¶
Runs tests in separate parallel processes. Since modern processors have multiple cores, this allows running tests significantly faster.
Using —parallel without a value, or with the value auto , runs one test process per core according to multiprocessing.cpu_count() . You can override this by passing the desired number of processes, e.g. —parallel 4 , or by setting the DJANGO_TEST_PROCESSES environment variable.
Django distributes test cases — unittest.TestCase subclasses — to subprocesses. If there are fewer test cases than configured processes, Django will reduce the number of processes accordingly.
Each process gets its own database. You must ensure that different test cases don’t access the same resources. For instance, test cases that touch the filesystem should create a temporary directory for their own use.
If you have test classes that cannot be run in parallel, you can use SerializeMixin to run them sequentially. See Enforce running test classes sequentially .
This option requires the third-party tblib package to display tracebacks correctly:
This feature isn’t available on Windows. It doesn’t work with the Oracle database backend either.
If you want to use pdb while debugging tests, you must disable parallel execution ( —parallel=1 ). You’ll see something like bdb.BdbQuit if you don’t.
When test parallelization is enabled and a test fails, Django may be unable to display the exception traceback. This can make debugging difficult. If you encounter this problem, run the affected test without parallelization to see the traceback of the failure.
This is a known limitation. It arises from the need to serialize objects in order to exchange them between processes. See What can be pickled and unpickled? for details.
Support for the value auto was added.
Runs only tests marked with the specified tags . May be specified multiple times and combined with test —exclude-tag .
Tests that fail to load are always considered matching.
In older versions, tests that failed to load did not match tags.
Excludes tests marked with the specified tags . May be specified multiple times and combined with test —tag .
Runs test methods and classes matching test name patterns, in the same way as unittest’s -k option . Can be specified multiple times.
Spawns a pdb debugger at each test error or failure. If you have it installed, ipdb is used instead.
Discards output ( stdout and stderr ) for passing tests, in the same way as unittest’s —buffer option .
Django automatically calls faulthandler.enable() when starting the tests, which allows it to print a traceback if the interpreter crashes. Pass —no-faulthandler to disable this behavior.
Outputs timings, including database setup and total run time.
testserver ¶
Runs a Django development server (as in runserver ) using data from the given fixture(s).
For example, this command:
…would perform the following steps:
- Create a test database, as described in The test database .
- Populate the test database with fixture data from the given fixtures. (For more on fixtures, see the documentation for loaddata above.)
- Runs the Django development server (as in runserver ), pointed at this newly created test database instead of your production database.
This is useful in a number of ways:
- When you’re writing unit tests of how your views act with certain fixture data, you can use testserver to interact with the views in a web browser, manually.
- Let’s say you’re developing your Django application and have a “pristine” copy of a database that you’d like to interact with. You can dump your database to a fixture (using the dumpdata command, explained above), then use testserver to run your web application with that data. With this arrangement, you have the flexibility of messing up your data in any way, knowing that whatever data changes you’re making are only being made to a test database.
Note that this server does not automatically detect changes to your Python source code (as runserver does). It does, however, detect changes to templates.
Specifies a different port, or IP address and port, from the default of 127.0.0.1:8000 . This value follows exactly the same format and serves exactly the same function as the argument to the runserver command.
To run the test server on port 7000 with fixture1 and fixture2 :
(The above statements are equivalent. We include both of them to demonstrate that it doesn’t matter whether the options come before or after the fixture arguments.)
To run on 1.2.3.4:7000 with a test fixture:
Suppresses all user prompts. A typical prompt is a warning about deleting an existing test database.
Commands provided by applications¶
Some commands are only available when the django.contrib application that implements them has been enabled . This section describes them grouped by their application.
django.contrib.auth ¶
changepassword ¶
This command is only available if Django’s authentication system ( django.contrib.auth ) is installed.
Allows changing a user’s password. It prompts you to enter a new password twice for the given user. If the entries are identical, this immediately becomes the new password. If you do not supply a user, the command will attempt to change the password whose username matches the current user.
Specifies the database to query for the user. Defaults to default .
createsuperuser ¶
This command is only available if Django’s authentication system ( django.contrib.auth ) is installed.
Creates a superuser account (a user who has all permissions). This is useful if you need to create an initial superuser account or if you need to programmatically generate superuser accounts for your site(s).
When run interactively, this command will prompt for a password for the new superuser account. When run non-interactively, you can provide a password by setting the DJANGO_SUPERUSER_PASSWORD environment variable. Otherwise, no password will be set, and the superuser account will not be able to log in until a password has been manually set for it.
In non-interactive mode, the USERNAME_FIELD and required fields (listed in REQUIRED_FIELDS ) fall back to DJANGO_SUPERUSER_<uppercase_field_name> environment variables, unless they are overridden by a command line argument. For example, to provide an email field, you can use DJANGO_SUPERUSER_EMAIL environment variable.
Suppresses all user prompts. If a suppressed prompt cannot be resolved automatically, the command will exit with error code 1.
—username USERNAME ¶ —email EMAIL ¶
The username and email address for the new account can be supplied by using the —username and —email arguments on the command line. If either of those is not supplied, createsuperuser will prompt for it when running interactively.
Specifies the database into which the superuser object will be saved.
You can subclass the management command and override get_input_data() if you want to customize data input and validation. Consult the source code for details on the existing implementation and the method’s parameters. For example, it could be useful if you have a ForeignKey in REQUIRED_FIELDS and want to allow creating an instance instead of entering the primary key of an existing instance.
django.contrib.contenttypes ¶
remove_stale_contenttypes ¶
This command is only available if Django’s contenttypes app ( django.contrib.contenttypes ) is installed.
Deletes stale content types (from deleted models) in your database. Any objects that depend on the deleted content types will also be deleted. A list of deleted objects will be displayed before you confirm it’s okay to proceed with the deletion.
Specifies the database to use. Defaults to default .
Deletes stale content types including ones from previously installed apps that have been removed from INSTALLED_APPS . Defaults to False .
django.contrib.gis ¶
ogrinspect ¶
This command is only available if GeoDjango ( django.contrib.gis ) is installed.
Please refer to its description in the GeoDjango documentation.
django.contrib.sessions ¶
clearsessions ¶
Can be run as a cron job or directly to clean out expired sessions.
django.contrib.sitemaps ¶
ping_google ¶
This command is only available if the Sitemaps framework ( django.contrib.sitemaps ) is installed.
Please refer to its description in the Sitemaps documentation.
django.contrib.staticfiles ¶
collectstatic ¶
This command is only available if the static files application ( django.contrib.staticfiles ) is installed.
Please refer to its description in the staticfiles documentation.
findstatic ¶
This command is only available if the static files application ( django.contrib.staticfiles ) is installed.
Please refer to its description in the staticfiles documentation.
Default options¶
Although some commands may allow their own custom options, every command allows for the following options by default:
Adds the given filesystem path to the Python import search path. If this isn’t provided, django-admin will use the PYTHONPATH environment variable.
This option is unnecessary in manage.py , because it takes care of setting the Python path for you.
Specifies the settings module to use. The settings module should be in Python package syntax, e.g. mysite.settings . If this isn’t provided, django-admin will use the DJANGO_SETTINGS_MODULE environment variable.
This option is unnecessary in manage.py , because it uses settings.py from the current project by default.
Displays a full stack trace when a CommandError is raised. By default, django-admin will show an error message when a CommandError occurs and a full stack trace for any other exception.
This option is ignored by runserver .
Specifies the amount of notification and debug information that a command should print to the console.
- 0 means no output.
- 1 means normal output (default).
- 2 means verbose output.
- 3 means very verbose output.
This option is ignored by runserver .
Disables colorized command output. Some commands format their output to be colorized. For example, errors will be printed to the console in red and SQL statements will be syntax highlighted.
Forces colorization of the command output if it would otherwise be disabled as discussed in Syntax coloring . For example, you may want to pipe colored output to another command.
Skips running system checks prior to running the command. This option is only available if the requires_system_checks command attribute is not an empty list or tuple.
Extra niceties¶
Syntax coloring¶
The django-admin / manage.py commands will use pretty color-coded output if your terminal supports ANSI-colored output. It won’t use the color codes if you’re piping the command’s output to another program unless the —force-color option is used.
Windows support¶
On Windows 10, the Windows Terminal application, VS Code, and PowerShell (where virtual terminal processing is enabled) allow colored output, and are supported by default.
Under Windows, the legacy cmd.exe native console doesn’t support ANSI escape sequences so by default there is no color output. In this case either of two third-party libraries are needed:
Install colorama, a Python package that translates ANSI color codes into Windows API calls. Django commands will detect its presence and will make use of its services to color output just like on Unix-based platforms. colorama can be installed via pip:
Install ANSICON, a third-party tool that allows cmd.exe to process ANSI color codes. Django commands will detect its presence and will make use of its services to color output just like on Unix-based platforms.
Other modern terminal environments on Windows, that support terminal colors, but which are not automatically detected as supported by Django, may “fake” the installation of ANSICON by setting the appropriate environmental variable, ANSICON=»on» .
Custom colors¶
The colors used for syntax highlighting can be customized. Django ships with three color palettes:
- dark , suited to terminals that show white text on a black background. This is the default palette.
- light , suited to terminals that show black text on a white background.
- nocolor , which disables syntax highlighting.
You select a palette by setting a DJANGO_COLORS environment variable to specify the palette you want to use. For example, to specify the light palette under a Unix or OS/X BASH shell, you would run the following at a command prompt:
You can also customize the colors that are used. Django specifies a number of roles in which color is used:
- error — A major error.
- notice — A minor error.
- success — A success.
- warning — A warning.
- sql_field — The name of a model field in SQL.
- sql_coltype — The type of a model field in SQL.
- sql_keyword — An SQL keyword.
- sql_table — The name of a model in SQL.
- http_info — A 1XX HTTP Informational server response.
- http_success — A 2XX HTTP Success server response.
- http_not_modified — A 304 HTTP Not Modified server response.
- http_redirect — A 3XX HTTP Redirect server response other than 304.
- http_not_found — A 404 HTTP Not Found server response.
- http_bad_request — A 4XX HTTP Bad Request server response other than 404.
- http_server_error — A 5XX HTTP Server Error response.
- migrate_heading — A heading in a migrations management command.
- migrate_label — A migration name.
Each of these roles can be assigned a specific foreground and background color, from the following list:
- black
- red
- green
- yellow
- blue
- magenta
- cyan
- white
Each of these colors can then be modified by using the following display options:
- bold
- underscore
- blink
- reverse
- conceal
A color specification follows one of the following patterns:
- role=fg
- role=fg/bg
- role=fg,option,option
- role=fg/bg,option,option
where role is the name of a valid color role, fg is the foreground color, bg is the background color and each option is one of the color modifying options. Multiple color specifications are then separated by a semicolon. For example:
would specify that errors be displayed using blinking yellow on blue, and notices displayed using magenta. All other color roles would be left uncolored.
Colors can also be specified by extending a base palette. If you put a palette name in a color specification, all the colors implied by that palette will be loaded. So:
would specify the use of all the colors in the light color palette, except for the colors for errors and notices which would be overridden as specified.
Bash completion¶
If you use the Bash shell, consider installing the Django bash completion script, which lives in extras/django_bash_completion in the Django source distribution. It enables tab-completion of django-admin and manage.py commands, so you can, for instance…
- Type django-admin .
- Press [TAB] to see all available options.
- Type sql , then [TAB], to see all available options whose names start with sql .
See How to create custom django-admin commands for how to add customized actions.
Black formatting¶
The Python files created by startproject , startapp , optimizemigration , makemigrations , and squashmigrations are formatted using the black command if it is present on your PATH .
If you have black globally installed, but do not wish it used for the current project, you can set the PATH explicitly:
For commands using stdout you can pipe the output to black if needed:
Running management commands from your code¶
To call a management command from code use call_command .
name the name of the command to call or a command object. Passing the name is preferred unless the object is required for testing. *args a list of arguments accepted by the command. Arguments are passed to the argument parser, so you can use the same style as you would on the command line. For example, call_command(‘flush’, ‘—verbosity=0’) . **options named options accepted on the command-line. Options are passed to the command without triggering the argument parser, which means you’ll need to pass the correct type. For example, call_command(‘flush’, verbosity=0) (zero must be an integer rather than a string).
Note that command options that take no arguments are passed as keywords with True or False , as you can see with the interactive option above.
Named arguments can be passed by using either one of the following syntaxes:
Some command options have different names when using call_command() instead of django-admin or manage.py . For example, django-admin createsuperuser —no-input translates to call_command(‘createsuperuser’, interactive=False) . To find what keyword argument name to use for call_command() , check the command’s source code for the dest argument passed to parser.add_argument() .
Command options which take multiple options are passed a list:
The return value of the call_command() function is the same as the return value of the handle() method of the command.
Output redirection¶
Note that you can redirect standard output and error streams as all commands support the stdout and stderr options. For example, you could write: