Django series: Django development environment configuration and the first Django project

Django series
Django development environment configuration and first Django project

Author : Li Juncai (jcLee95) : https://blog.csdn.net/qq_28550263
Email: [email protected]
Article address : https://blog.csdn.net/qq_28550263/article/details/132892113


【介绍】:Django开发环境配置与第一个Django项目的搭建。包括虚拟隔离环境,命令行工具的使用等。

Previous section: " Introduction to Django and Overview of MTV Architecture System " | Next section: " Django Project Structure and Configuration Analysis "

Insert image description here


1 Overview

This article will explain how to install Python, including choosing the appropriate version and download source. We'll then delve into the concept of virtual environments, explaining why virtual isolation environments are critical to a project's isolation and dependency management. You'll learn how to create a virtual environment using Python's venvtools and learn how to activate it and install Django.

Next, this article will discuss the usage of Django's command line tools in detail django-admin, and explain the functions and usage of various commonly used commands, including database migration, server startup, application creation, etc.

Finally, this article will explore the concepts of "Project" and "App" in Django projects to help developers better organize and manage the various components of their Django projects.

2. Installation of Python development environment

This series of articles is based on Python3, so make sure that the Python version you install is consistent.

3. Python virtual isolation environment and its creation

3.1 What is a virtual isolation environment?

The concept of virtual isolation environment

Python Virtual Isolation Environment is a tool for isolating Python dependencies and libraries of different projects. This allows you to run different versions of Python and the dependencies required by different projects on the same machine without conflicts. Virtual environments help maintain the independence of projects and ensure that dependencies between projects do not interfere with each other.

Why is it recommended to use a virtual isolation environment?

First of all, from the perspective of dependency isolation, different projects may require different versions of Python libraries and dependencies. By creating virtual environments, you can manage dependencies for each project individually, ensuring that libraries between projects don't conflict. This helps avoid breaking dependencies in one project when updating another.

Then, from a version compatibility perspective, some projects may require a specific version of Python. Virtual environments allow you to run multiple Python versions simultaneously on the same computer without interfering with each other. This is important for maintaining legacy code or for compatibility testing with new versions of Python.
From the perspective of project independence, the virtual environment isolates each project so that it can manage its Python environment independently. This means you can install the libraries you need for a specific project without worrying about them affecting other projects. This helps keep the project clean and independent.

Secondly, from the perspective of isolating system Python, system Python is usually used for operating system level tasks, and changing system Python may cause instability and problems. By using a virtual environment, you avoid interfering with system Python because virtual environments are project-specific.

Virtual environments can be easily shared with other developers or deployment environments. You can share the virtual environment's configuration file (such as requirements.txt) with others to ensure that they can run the project in the same environment.

By using a virtual environment, you can keep your development environment clean and avoid installing numerous libraries and dependencies globally. This makes it more convenient when switching between different projects.

Additionally, virtual environments make it easier to perform unit and integration testing in projects. You can create a separate virtual environment for testing to ensure that your tests are not affected by other projects.

3.2 venv usage analysis

venv is a module of Python used to create and manage virtual environments. It does not need to be installed separately. The venv module provides a command line tool to create virtual Python environments in one or more target directories through commands. . Its usage format is:

venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear] [--upgrade] [--without-pip]
            [--prompt PROMPT] [--upgrade-deps]
            ENV_DIR [ENV_DIR ...]

Among them, the positional parameters:

  • ENV_DIR: Indicates the directory where the environment is to be created.

This command has the following options:

  • -h, --helpdisplay help message and exit
  • --system-site-packagesIndicates that the virtual environment is allowed to access packages in the system site-packages directory.
  • --symlinksTry using symlinks instead of copying files if it is not the platform default.
  • --copiesAttempts to use copy files even when the platform defaults to using symlinks.
  • --clearBefore creating the environment, delete the contents of the environment directory if it already exists.
  • --upgradeUpgrade the environment directory to use this version of Python, assuming Python has been upgraded in place.
  • --without-pipSkip installing or upgrading pip in a virtual environment (pip will be booted and installed by default).
  • --prompt PROMPTProvide an alternative prompt prefix for this environment.
  • --upgrade-depsUpgrade core dependencies: pip and setuptools to the latest versions in PyPI.

3.3 Create a virtual isolation environment for the Django project

To venvcreate a virtual isolation environment and develop your first Django project in it, you can follow these steps:

1. Create project directory

First, create a new directory to house your Django project. mkdirYou can create a new directory using commands on the command line , for example:

mkdir mydjango_project
cd mydjango_project

2. Create a virtual environment

In the project directory, use venvthe command to create a new virtual environment. The name of the virtual environment is usually env, but you can choose another name for it if needed:

python -m venv env

envThis will create a virtual environment called in the project directory .

3. Activate the virtual environment

After creating the virtual environment, you need to activate it so that Django and other dependencies can be installed in it. Run the following command on the command line:

  • On Windows:

    # 也就是.\env\Scripts\activate
    env\Scripts\activate
    
  • On Linux:

    source env/bin/activate
    

(env)After activating the virtual environment, you will see the name of the virtual environment (for example, ) in front of the command line prompt , indicating that the virtual environment has taken effect.

Insert image description here

4. Install Django

In the activated virtual environment, pipinstall Django using

pip install django

This will install the latest version of Django.

5. Create a Django project

django-adminNow, you can create a new Django project using the command in your project directory :

django-admin startproject myproject

Note that if you are using system Python, the django-admin tool is located in the script directory of the system Python, which requires the script directory of the system Python to be added to the system's path environment variable (the same is true for the pip command of the system Python, which is actually an executable file over there). If it is Python in a virtual isolation environment, use django-admin, pipetc., there is no need to add the isolation environment Python to the system path environment variable. Instead, use the method introduced above to enter the corresponding Python virtual isolation environment.

This will create a myprojectDjango project named and generate relevant files and directories in the project directory.

Step 6: Run the development server

Enter the Django project directory:

cd myproject

Then run Django's development server:

python manage.py runserver

This will start the development server, listening on by default http://127.0.0.1:8000/.

Note: You can also specify the port yourself, just add the port number you want to specify at the end. For example, if you specify to listen for web requests on port 8001, you only need to run the command:

python manage.py runserver 8001

After running, you will see some prompts:

You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.

This prompt is provided by Django's migration system, which indicates that there are some database migrations that have not yet been applied to the database. Database migration is used to manage database schema (structure) changes, including operations such as creating tables, modifying table structures, and adding fields.

But this does not prevent us from seeing Django’s own initial interface. Of course, you can also execute the following command before running:

python manage.py migrate

The migrate command will synchronize the database structure with your Django models based on the migration files in your Django application. When you create a new Django project, there are usually some initial migration files used to create the database tables required by Django's built-in applications (such as admin, auth, contenttypes, sessions).

Insert image description here
So, if you see this prompt, the usual approach is to run python manage.py migrate to apply these unapplied migrations. This way, Django will create or update the database table to reflect your model definition. After this, your Django project should work fine.

如果你在运行migrate命令时遇到任何错误,请检查错误消息以了解问题的具体原因,然后根据错误消息采取相应的措施来解决问题。通常情况下,这些错误可以通过修改模型定义或迁移文件来解决。

步骤 7:访问Django项目

现在,你可以在浏览器中访问http://127.0.0.1:8000/,看到你的Django项目正在运行。

Insert image description here

如果你也看到了这个界面,那么恭喜你,你已经成功创建了一个虚拟隔离环境,并在其中开发了一个Django项目。

4. django-admin命令行工具解析

4.1 功能概述

django-admin 是 Django 的命令行工具,它用于执行各种 Django 相关的任务和管理 Django 项目。在全局环境下,通过Python的脚本目录中的django-admin可执行文件运行该命令行工具;而一旦项目创建,则可以通过在当前Django项目下,使用 python manage.py xxx运行相同命令。

要注意的是,如果在虚拟隔离环境中,你需要先激活相应的虚拟隔离环境。

django-admin提供的命令及其对应的功能如下表所示:

命令 功能
check 检查项目中的问题和错误,例如未使用的导入、命名冲突等
compilemessages 编译翻译文件供国际化使用
createcachetable 在数据库中创建缓存表
dbshell 通过数据库客户端访问数据库
diffsettings 比较当前设置和默认设置文件之间的差异
dumpdata 将数据转储到文件中,以备将来使用
flush 清空数据库中的所有数据
inspectdb 根据数据库结构生成模型代码
loaddata 从文件中加载数据到数据库
makemessages 从Django代码中提取可翻译的文本,并创建翻译文件
makemigrations 根据模型的变更生成数据库迁移文件
migrate 将数据库迁移到最新模型状态
optimizemigration 优化数据库迁移以提高性能
runserver 启动开发服务器以在本地运行Django应用程序
sendtestemail 发送测试电子邮件以检查电子邮件配置
shell Enter an interactive Python shell environment where Django projects and models can be accessed
showmigrations Show migration status in activities and applications
sqlflush Generate SQL statements for clearing the database
sqlmigrate Generate and execute SQL statements based on migration files
sqlsequencereset Resets the serial number for the given model
squashmigrations Combine multiple migration files into one file
startup app Create a new Django application
starting project Create a new Django project
test Running tests for Django applications
test server Start a development server for running tests of your Django application

4.2 check command

django-admin checkUsed to check the entire Django project for potential problems and errors. Its syntax format is as follows:

django-admin check [-h] [--tag TAGS] [--list-tags] [--deploy]
                   [--fail-level {
    
    CRITICAL,ERROR,WARNING,INFO,DEBUG}] [--database DATABASES] [--version]
                   [-v {
    
    0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color]
                   [--force-color]
                   [app_label ...]

Among them, positional parameters (Positional Arguments) :

  • app_label: Optional parameter, indicating the name of the application to be checked. If one or more app names are provided, checkthe command will only check for issues with those apps. If no app name is specified, the entire project is checked.

Options :

  • -h, --help: Display help message and exit.

  • --tag TAGS, -t TAGS: Run only checks with the specified label. Tags are used to group exams, and you can choose to run exams for specific tags. For example, --tag securityonly security-related checks will be run.

  • --list-tags: List available tags. This option will display a list of tags available in the project so you can choose to run checks for the relevant tags.

  • --deploy: Check deployment settings. Using this option runs deployment-related checks to ensure that your project settings meet deployment requirements.

  • --fail-level {CRITICAL,ERROR,WARNING,INFO,DEBUG}:Specifies the message level that causes the command to exit with a non-zero status. The default level is ERROR, which means the command will only exit if an error is found.

  • --database DATABASES:Specifies the database alias on which to run database-related checks. This allows you to run checks for a specific database configuration, --database defaulte.g.

  • --version: Display the program version number and exit.

  • -v {0,1,2,3}, --verbosity {0,1,2,3}: Set the verbosity of the command. Optional values ​​are 0 (minimum output), 1 (normal output), 2 (verbose output), and 3 (very detailed output).

  • --settings SETTINGS:Specify the Python path of a settings module, for example, "myproject.settings.main". If this option is not provided, DJANGO_SETTINGS_MODULEthe settings module specified in the environment variable will be used.

  • --pythonpath PYTHONPATH: Directory to add to the Python path. This allows you to specify additional directories so that the command can find relevant files for your project.

  • --traceback: CommandErrorRaise an exception when an exception occurs to provide more detailed error information.

  • --no-color: Disable colorization of command output.

  • --force-color: Force colorization of command output.

django-admin checkCommand is a very useful tool that can help you find potential problems and errors in your project, including database-related issues, deployment settings issues, security issues, etc. By checking your project, you can ensure its health and reduce potential errors. You can use various options to customize the scope and level of detail of the inspection as needed.

4.3 compilemessages command

django-admin compilemessagesUsed to .pocompile a file into .moa file for use by the built-in gettext support. gettext is an internationalization and localization tool used to support multi-language translation in Django projects. Its syntax format is as follows:

django-admin compilemessages [-h] [--locale LOCALE] [--exclude EXCLUDE] [--use-fuzzy] [--ignore PATTERN]
                             [--version] [-v {
    
    0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH]
                             [--traceback] [--no-color] [--force-color]

Options :

  • -h, --help: Display help message and exit.

  • --locale LOCALE, -l LOCALE: Specify the locale (Locale) to be processed. By default, all available locales will be processed, but you can use this option to specify one or more locales, --locale de_ATe.g.

  • --exclude EXCLUDE, -x EXCLUDE: Specifies the locales to exclude. By default, no locales are excluded, but you can use this option to exclude locales that do not need to be processed, --exclude es_ESe.g.

  • --use-fuzzy, -f: Use fuzzy translation. If this option is enabled, the compilation process will generate files using translations marked as ambiguous .mo. Fuzzy translation is a flag in a translation file that indicates the translation may not be completely accurate and requires further review.

  • --ignore PATTERN, -i PATTERN: Specify directories to ignore, which can be matched using wildcard-like patterns. You can use this option multiple times to specify multiple directories to ignore.

  • --version: Display the program version number and exit.

  • -v {0,1,2,3}, --verbosity {0,1,2,3}: Set the verbosity of the command. Optional values ​​are 0 (minimum output), 1 (normal output), 2 (verbose output), and 3 (very detailed output).

  • --settings SETTINGS:Specify the Python path of a settings module, for example, "myproject.settings.main". If this option is not provided, DJANGO_SETTINGS_MODULEthe settings module specified in the environment variable will be used.

  • --pythonpath PYTHONPATH: Directory to add to the Python path. This allows you to specify additional directories so that the command can find relevant files for your project.

  • --traceback: CommandErrorRaise an exception when an exception occurs to provide more detailed error information.

  • --no-color: Disable colorization of command output.

  • --force-color: Force colorization of command output.

django-admin compilemessages.poThe command is used to compile text translations in Django projects from .mofiles into files that contain translated text in different languages ​​to support multilingual applications. Typically, this command is used during internationalization and localization development to provide translations in different locales.

4.4 createcachetable command

django-admin createcachetableis a command in Django that is used to create the cache tables required when using the SQL cache backend. Its syntax format is as follows:

django-admin createcachetable [-h] [--database DATABASE] [--dry-run] [--version] [-v {
    
    0,1,2,3}]
                              [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color]
                              [--force-color]
                              [table_name ...]

in:

Positional Arguments :

  • table_name: Optional parameter, indicating the name of the cache table to be created. CACHESIf no table name is provided, the configuration in the project's settings file will be used to determine the name of the cache table.

Options :

  • -h, --help: Display help message and exit.

  • --database DATABASE: Specify the database where cache tables are to be installed. By default, cache tables will be installed on the database named "default".

  • --dry-run: Does not create a table, only prints the SQL statement to be executed. Use this option to preview the SQL statement that will be run without actually creating the table.

  • --version: Display the program version number and exit.

  • -v {0,1,2,3}, --verbosity {0,1,2,3}: Set the verbosity of the command. Optional values ​​are 0 (minimum output), 1 (normal output), 2 (verbose output), and 3 (very detailed output).

  • --settings SETTINGS:Specify the Python path of a settings module, for example, "myproject.settings.main". If this option is not provided, DJANGO_SETTINGS_MODULEthe settings module specified in the environment variable will be used.

  • --pythonpath PYTHONPATH: Directory to add to the Python path. This allows you to specify additional directories so that the command can find relevant files for your project.

  • --traceback: CommandErrorRaise an exception when an exception occurs to provide more detailed error information.

  • --no-color: Disable colorization of command output.

  • --force-color: Force colorization of command output.

django-admin createcachetableCommand is used to create the cache tables required when using the SQL cache backend. These tables are used to store cached data in order to speed up the performance of Django applications. You can use this command to create a cache table to use caching functionality in your project. Normally, you don't need to run this command manually because Django will automatically create cache tables when needed.

4.5 dbshell command

The dbshell command of django-admin is used to start a command line client for the specified database, or default to the default database if no database name is provided. Its syntax format is as follows:

django-admin dbshell [-h] [--database DATABASE] [--version] [-v {
    
    0,1,2,3}] [--settings SETTINGS]
                     [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--force-color]
                     [parameters ...]

Among them:
Options :

  • -h, --help: Display help message and exit.

  • --database DATABASE: Specify the database to open the command line client. By default, the database named "default" will be used.

  • --version: Display the program version number and exit.

  • -v {0,1,2,3}, --verbosity {0,1,2,3}: Set the verbosity of the command. Optional values ​​are 0 (minimum output), 1 (normal output), 2 (verbose output), and 3 (very detailed output).

  • --settings SETTINGS:Specify the Python path of a settings module, for example, "myproject.settings.main". If this option is not provided, DJANGO_SETTINGS_MODULEthe settings module specified in the environment variable will be used.

  • --pythonpath PYTHONPATH: Directory to add to the Python path. This allows you to specify additional directories so that the command can find relevant files for your project.

  • --traceback: CommandErrorRaise an exception when an exception occurs to provide more detailed error information.

  • --no-color: Disable colorization of command output.

  • --force-color: Force colorization of command output.

Parameters :

  • parameters: Optional parameter for additional parameters passed to the database command line client. These parameters are typically options specific to the database command line client, such as username, password, etc.

django-admin dbshellCommands allow you to access the database through the command line to perform SQL queries and other database operations. You can use --databasethe options to specify the database to connect to, and you can parameterspass other database client-specific parameters in the parameters. This command is very useful for debugging and maintaining the database.

4.6 diffsettings command

django-admin diffsettingsThe command displays settings.pythe differences between the current project's settings file ( ) and Django's default settings. Its syntax format is:

django-admin diffsettings [-h] [--all] [--default MODULE] [--output {
    
    hash,unified}] [--version]
                          [-v {
    
    0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback]
                          [--no-color] [--force-color]

in:

Options :

  • -h, --help: Display help message and exit.

  • --all: Shows all settings regardless of their value. In "hash" mode, the default value is displayed with a "###" prefix.

  • --default MODULE:Specifies the default settings module to which the current settings are compared. If this option is not provided, the default will be compared to Django's default settings.

  • --output {hash,unified}: Select the output format. 'hash' mode shows each changed setting, settings not in the default settings are shown with a "###" prefix. 'unified' mode uses a minus sign prefix to indicate the default settings, followed by a plus sign prefix to indicate changed settings.

  • --version: Display the program version number and exit.

  • -v {0,1,2,3}, --verbosity {0,1,2,3}: Set the verbosity of the command. Optional values ​​are 0 (minimum output), 1 (normal output), 2 (verbose output), and 3 (very detailed output).

  • --settings SETTINGS:Specify the Python path of a settings module, for example, "myproject.settings.main". If this option is not provided, DJANGO_SETTINGS_MODULEthe settings module specified in the environment variable will be used.

  • --pythonpath PYTHONPATH: Directory to add to the Python path. This allows you to specify additional directories so that the command can find relevant files for your project.

  • --traceback: CommandErrorRaise an exception when an exception occurs to provide more detailed error information.

  • --no-color: Disable colorization of command output.

  • --force-color: Force colorization of command output.

django-admin diffsettingsThe command is used to compare the differences between the current project's settings file and Django's default settings. It's useful for seeing which settings have been changed to meet project needs. You can choose different output formats to see the differences in settings more clearly.

4.7 dumpdata command

dumpdataThe command is used to output the contents of the database in a specified format, and the output result can be used as a fixture. By default, each model uses its default manager for output unless --allthe parameter is specified.
Its syntax format is:

django-admin dumpdata [-h] [--format FORMAT] [--indent INDENT] [--database DATABASE] [-e EXCLUDE]
                       [--natural-foreign] [--natural-primary] [-a] [--pks PRIMARY_KEYS] [-o OUTPUT]
                       [--version] [-v {
    
    0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH]
                       [--traceback] [--no-color] [--force-color] [--skip-checks]
                       [app_label[.ModelName] ...]

in

Options :

  • app_label[.ModelName]: Limit the output data to the specified app_label or app_label.ModelName.
  • --format FORMAT: Specify the output serialization format.
  • --indent INDENT: Specify the indentation level during output.
  • --database DATABASE: Specify which database to export fixtures from, the default is the "default" database.
  • -e EXCLUDE, --exclude EXCLUDE: app_label or app_label.ModelName to be excluded (multiple can be used to --excludeexclude multiple apps or models).
  • --natural-foreign: Use natural foreign keys if available.
  • --natural-primary: Use natural primary key if available.
  • -a, --all: Use Django's base manager to output data for all models in the database, including those filtered or modified by custom managers.
  • --pks PRIMARY_KEYS: Output only objects with the specified primary key. Accepts a comma separated list of primary keys. This option is only effective when specifying a model.
  • -o OUTPUT, --output OUTPUT: Specify the file to which the output results are written.
  • --version: Display the program version number and exit.
  • -v {0,1,2,3}, --verbosity {0,1,2,3}: Set the output level; 0=minimum output, 1=normal output, 2=verbose output, 3=very detailed output.
  • --settings SETTINGS: Specify the Python path of a settings module, such as "myproject.settings.main". If this parameter is not provided, the DJANGO_SETTINGS_MODULE environment variable will be used.
  • --pythonpath PYTHONPATH: Directory added to the Python path, such as "/home/djangoprojects/myproject".
  • --traceback: Throws an exception when a command error exception occurs.
  • --no-color: Do not colorize command output.
  • --force-color: Forces coloring of command output.
  • --skip-checks: Skip system check.

The above is django-admin dumpdatathe detailed description of the command. You can use the corresponding options to export the database content as needed.

4.8 flush command

django-admin flushCommand is used to delete all data from the database, including data added during migration. It should be noted that this command will not restore the database to a "new installation" state, but only clears the data in the database without affecting other content such as the table structure. The following is django-admin flushan analysis of the parameters and options of the command: its syntax format is:

django-admin flush [-h] [--noinput] [--database DATABASE] [--version] [-v {
    
    0,1,2,3}] [--settings SETTINGS]
                   [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--force-color] [--skip-checks]

in:

Options :

  • -h, --help: Display help message and exit.

  • --noinput, --no-input: Tells Django not to prompt the user for any input. If this option is not used, the command will ask the user to confirm deletion of all data.

  • --database DATABASE: Specify the database to perform flush operation. By default, the database named "default" will be used.

  • --version: Display the program version number and exit.

  • -v {0,1,2,3}, --verbosity {0,1,2,3}: Set the verbosity of the command. Optional values ​​are 0 (minimum output), 1 (normal output), 2 (verbose output), and 3 (very detailed output).

  • --settings SETTINGS:Specify the Python path of a settings module, for example, "myproject.settings.main". If this option is not provided, DJANGO_SETTINGS_MODULEthe settings module specified in the environment variable will be used.

  • --pythonpath PYTHONPATH: Directory to add to the Python path. This allows you to specify additional directories so that the command can find relevant files for your project.

  • --traceback: CommandErrorRaise an exception when an exception occurs to provide more detailed error information.

  • --no-color: Disable colorization of command output.

  • --force-color: Force colorization of command output.

  • --skip-checks: Skip system check. Use this option if you wish to ignore system checks and perform a flush operation.

django-admin flushCommands are typically used to clear data in a development or test database in order to start over or repopulate the data. Use with caution as it will delete all data including user data, test data, etc.

4.9 inspectdb command

django-admin inspectdbThe command is used to check the tables or views in the specified database and generate the corresponding Django model based on the database structure. Its syntax format is:

django-admin inspectdb [-h] [--database DATABASE] [--include-partitions] [--include-views] [--version]
                       [-v {
    
    0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback]
                       [--no-color] [--force-color]
                       [table ...]

in:

Positional Arguments :

  • table: Optional parameter, select the table or view to be checked. If no table name is provided, all tables and views are checked by default.

Options :

  • -h, --help: Display help message and exit.

  • --database DATABASE:Specify the database to perform the check. By default, the database named "default" will be used.

  • --include-partitions: Output the model of the partition table. If a partitioned table exists in the database, using this option will generate the corresponding model.

  • --include-views: Output the model of the database view. If a view exists in the database, using this option will generate the corresponding model.

  • --version: Display the program version number and exit.

  • -v {0,1,2,3}, --verbosity {0,1,2,3}: Set the verbosity of the command. Optional values ​​are 0 (minimum output), 1 (normal output), 2 (verbose output), and 3 (very detailed output).

  • --settings SETTINGS:Specify the Python path of a settings module, for example, "myproject.settings.main". If this option is not provided, DJANGO_SETTINGS_MODULEthe settings module specified in the environment variable will be used.

  • --pythonpath PYTHONPATH: Directory to add to the Python path. This allows you to specify additional directories so that the command can find relevant files for your project.

  • --traceback: CommandErrorRaise an exception when an exception occurs to provide more detailed error information.

  • --no-color: Disable colorization of command output.

  • --force-color: Force colorization of command output.

django-admin inspectdbCommand is used to automatically generate code for Django models that correspond to tables or views in the specified database. This is useful for reverse engineering existing databases as it reduces the effort of manually writing the model. The generated model code can be used to access and manipulate data from database tables or views in Django projects.

4.10 loaddata command

django-admin loaddataThe command is used to load the specified data fixture file into the database. These fixture files contain predefined data that can be used to initialize the database or populate database tables. Its syntax format is:

django-admin loaddata [-h] [--database DATABASE] [--app APP_LABEL] [--ignorenonexistent] [-e EXCLUDE]
                      [--format FORMAT] [--version] [-v {
    
    0,1,2,3}] [--settings SETTINGS]
                      [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--force-color] [--skip-checks]
                      fixture [fixture ...]

in:

Positional Arguments :

  • fixture: Fixture tags to be loaded, one or more can be specified. Fixture tags usually correspond to files containing predefined data.

Options :

  • -h, --help: Display help message and exit.

  • --database DATABASE: Specify the database to load fixture data. By default, the database named "default" will be used.

  • --app APP_LABEL: Find fixtures only in the specified application. You can use this option to limit the fixture search scope.

  • --ignorenonexistent, -i: Ignore fields that exist in the serialized data but not in the current model. Use this option to prevent fixture loading failures due to model changes.

  • -e EXCLUDE, --exclude EXCLUDE: Exclude specified applications or models. Can be used multiple times to exclude multiple applications or models.

  • --format FORMAT: Specifies the serialization format when reading data from standard input.

  • --version: Display the program version number and exit.

  • -v {0,1,2,3}, --verbosity {0,1,2,3}: Set the verbosity of the command. Optional values ​​are 0 (minimum output), 1 (normal output), 2 (verbose output), and 3 (very detailed output).

  • --settings SETTINGS:Specify the Python path of a settings module, for example, "myproject.settings.main". If this option is not provided, DJANGO_SETTINGS_MODULEthe settings module specified in the environment variable will be used.

  • --pythonpath PYTHONPATH: Directory to add to the Python path. This allows you to specify additional directories so that the command can find relevant files for your project.

  • --traceback: CommandErrorRaise an exception when an exception occurs to provide more detailed error information.

  • --no-color: Disable colorization of command output.

  • --force-color: Force colorization of command output.

  • --skip-checks: Skip system check. Use this option if you wish to ignore system checks and perform fixture loading instead.

django-admin loaddataCommands are typically used to initialize the database or add predefined data to the database. The fixture file contains a serialized representation of the model data, which can automatically populate the database table without manually adding data.

4.11 makemessages command

django-admin makemessagesThe command is used to extract strings marked as requiring translation from the code and create or update the corresponding translation files. Its syntax format is:

django-admin makemessages [-h] [--locale LOCALE] [--exclude EXCLUDE] [--domain DOMAIN] [--all]
                          [--extension EXTENSIONS] [--symlinks] [--ignore PATTERN] [--no-default-ignore]
                          [--no-wrap] [--no-location] [--add-location [{
    
    full,file,never}]] [--no-obsolete]
                          [--keep-pot] [--version] [-v {
    
    0,1,2,3}] [--settings SETTINGS]
                          [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--force-color]

in:

  • --locale LOCALE, -l LOCALE: Specify the language code to create or update. You can use this option multiple times to specify multiple languages.
  • --exclude EXCLUDE, -x EXCLUDE: Specify the language codes to be excluded, the default is None. You can use this option multiple times to exclude multiple languages.
  • --domain DOMAIN, -d DOMAIN: Specify the domain of the translation file, the default is "django".
  • --all, -a: Update translation files for all existing languages.
  • --extension EXTENSIONS, -e EXTENSIONS: The file extension to check, the default is "html,txt,py", or "js" if the domain is "djangojs". You can use commas to separate multiple extensions, or use multiple times to -especify multiple extensions.
  • --symlinks, -s: Directory to follow symlinks when inspecting source code and templates in order to extract translation strings.
  • --ignore PATTERN, -i PATTERN: Ignore files or directories matching the specified pattern. This option can be used multiple times to ignore more files.
  • --no-default-ignore: Don't ignore common patterns like 'CVS', '. ', ' ~' and '*.pyc'.
  • --no-wrap: Do not split long message lines into multiple lines.
  • --no-location: Do not write the '#:filename:linenumber' line.
  • --add-location [{full,file,never}]: Control the '#:filename:linenumber' line. If the option is 'full' (defaults to 'full' if no option is specified), the line number contains the file name and line number. If 'file', the line number is omitted. If 'never', no line numbers are displayed ( --no-locationsame as ). --add-locationRequires gettext 0.19 or higher.
  • --no-obsolete: Remove outdated translation strings.
  • --keep-pot: Preserve the .pot file after generating the translation file for debugging.
  • --version: Display the program version number and exit.
  • -v {0,1,2,3}, --verbosity {0,1,2,3}: Specifies the verbosity level of the output; 0=minimum output, 1=normal output, 2=verbose output, 3=very verbose output.
  • --settings SETTINGS: Specify the Python path of a settings module, such as "myproject.settings.main". If this option is not provided, the DJANGO_SETTINGS_MODULE environment variable will be used.
  • --pythonpath PYTHONPATH: Directory to add to the Python path, such as "/home/djangoprojects/myproject".
  • --traceback: Throws an exception when a CommandError exception occurs.
  • --no-color: Do not color command output
  • --force-color: Forces coloring of command output.

Hope this information is helpful!

4.12 makemigrations command

django-admin makemigrationsCommand is used to create a new database migration file for the application. Its syntax format is:

django-admin makemigrations [-h] [--dry-run] [--merge] [--empty] [--noinput] [-n NAME] [--no-header]
                            [--check] [--scriptable] [--update] [--version] [-v {
    
    0,1,2,3}]
                            [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color]
                            [--force-color] [--skip-checks]
                            [app_label ...]

in

Positional Arguments :

  • app_label:Specifies the application tag for which you want to create a migration. You can provide one or more application labels, separated by spaces.

Options :

  • -h, --help: Display help message and exit.

  • --dry-run: Only shows the migrations that will be generated without actually generating them.

  • --merge: Enables the ability to resolve migration conflicts. Used to merge multiple migration files into one.

  • --empty:Creates an empty migration file, typically used for manual editing.

  • --noinput, --no-input: Tells Django not to prompt the user for any input.

  • -n NAME, --name NAME: Specify the name of the migration file. Can be used to customize the naming of migration files.

  • --no-header: Do not add header comments in new migration files.

  • --check: Exits with a non-zero status if the model change is missing a migration and does not actually create a migration.

  • --scriptable: Redirect log output and input prompts to stderr, and write only the path to the generated migration file to stdout.

  • --update: Merge model changes into the latest migration file and optimize the resulting operations.

  • --version: Display the program version number and exit.

  • -v {0,1,2,3}, --verbosity {0,1,2,3}: Set the verbosity of the command. Optional values ​​are 0 (minimum output), 1 (normal output), 2 (verbose output), and 3 (very detailed output).

  • --settings SETTINGS:Specify the Python path of a settings module, for example, "myproject.settings.main". If this option is not provided, DJANGO_SETTINGS_MODULEthe settings module specified in the environment variable will be used.

  • --pythonpath PYTHONPATH: Directory to add to the Python path. This allows you to specify additional directories so that the command can find relevant files for your project.

  • --traceback: CommandErrorRaise an exception when an exception occurs to provide more detailed error information.

  • --no-color: Disable colorization of command output.

  • --force-color: Force colorization of command output.

  • --skip-checks: Skip system check. Use this option if you wish to ignore system checks and perform a create migration operation.

django-admin makemigrationsThe command is typically used to create database migration files related to model changes in order to apply those changes to the database.

4.13 migrate command

django-admin migrateCommand is used to update the schema of the database. It manages applications with migration as well as applications without migration. The following syntax format is:

django-admin migrate [-h] [--noinput] [--database DATABASE] [--fake] [--fake-initial] [--plan]
                     [--run-syncdb] [--check] [--prune] [--version] [-v {
    
    0,1,2,3}] [--settings SETTINGS]
                     [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--force-color] [--skip-checks]
                     [app_label] [migration_name]

in:

Positional Arguments :

  • app_label: Application label, indicating the application whose status is to be synchronized. You can specify one or more application tags.
  • migration_name: The database status will be adjusted to the status after migration. Use "zero" as the name to unapply all migrations.

Options :

  • -h, --help: Display help message and exit.

  • --noinput, --no-input: Tells Django not to prompt the user for any input.

  • --database DATABASE: Specify the database to be synchronized. By default, the database named "default" will be used.

  • --fake: Marks migrations as running, but doesn't actually run them. This is typically used to mark that previous migrations have been applied, but the database schema does not require changes.

  • --fake-initial: Check whether the table already exists. If it exists, simulate the application of initial migration. Before using this flag, make sure the current database schema matches the initial migration.

  • --plan: Displays a list of migration operations that will be performed without actually executing them.

  • --run-syncdb:Create tables for applications without migration.

  • --check: If there are unapplied migrations, exit with a non-zero status without actually applying the migrations.

  • --prune: django_migrationsDelete non-existing migration records from the table.

  • --version: Display the program version number and exit.

  • -v {0,1,2,3}, --verbosity {0,1,2,3}: Set the verbosity of the command. Optional values ​​are 0 (minimum output), 1 (normal output), 2 (verbose output), and 3 (very detailed output).

  • --settings SETTINGS:Specify the Python path of a settings module, for example, "myproject.settings.main". If this option is not provided, DJANGO_SETTINGS_MODULEthe settings module specified in the environment variable will be used.

  • --pythonpath PYTHONPATH: Directory to add to the Python path. This allows you to specify additional directories so that the command can find relevant files for your project.

  • --traceback: CommandErrorRaise an exception when an exception occurs to provide more detailed error information.

  • --no-color: Disable colorization of command output.

  • --force-color: Force colorization of command output.

  • --skip-checks: Skip system check. Use this option if you wish to ignore system checks and perform the migration operation.

django-admin migrateThe command is typically used to apply database migrations to ensure that the database's schema is consistent with the current code state. This command performs the migration operations defined in each application, updating the database to a state that matches the project code.

4.14 optimizemigration command

django-admin optimizemigrationCommands are used to optimize the operation of specified migrations. Its syntax format is:

django-admin optimizemigration [-h] [--check] [--version] [-v {
    
    0,1,2,3}] [--settings SETTINGS]
                               [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--force-color]
                               [--skip-checks]
                               app_label migration_name

in:

Positional Arguments :

  • app_label: The label of the application for which migration operations are to be optimized.
  • migration_name: The name of the migration to be optimized.

Options :

  • -h, --help: Display help message and exit.

  • --check: If the migration can be optimized, exit with a non-zero status. This option is used to check whether the migration can be optimized without performing actual optimization operations.

  • --version: Display the program version number and exit.

  • -v {0,1,2,3}, --verbosity {0,1,2,3}: Set the verbosity of the command. Optional values ​​are 0 (minimum output), 1 (normal output), 2 (verbose output), and 3 (very detailed output).

  • --settings SETTINGS:Specify the Python path of a settings module, for example, "myproject.settings.main". If this option is not provided, DJANGO_SETTINGS_MODULEthe settings module specified in the environment variable will be used.

  • --pythonpath PYTHONPATH: Directory to add to the Python path. This allows you to specify additional directories so that the command can find relevant files for your project.

  • --traceback: CommandErrorRaise an exception when an exception occurs to provide more detailed error information.

  • --no-color: Disable colorization of command output.

  • --force-color: Force colorization of command output.

  • --skip-checks: Skip system check. Use this option if you wish to ignore system checks and perform migration optimization operations.

django-admin optimizemigrationCommands are typically used to analyze and optimize database operations for a specified migration. It can help you understand whether it is possible to optimize migration operations to reduce the complexity of database operations or improve performance. If you suspect that a migration may need optimization, you can use this command to inspect and analyze it.

4.15 runserver command

django-admin runserverThe command is used to start a lightweight development web server. Its syntax format is:

django-admin runserver [-h] [--ipv6] [--nothreading] [--noreload] [--version] [--settings SETTINGS]
                       [--pythonpath PYTHONPATH] [--no-color] [--force-color] [--skip-checks]
                       [addrport]

in:

Positional Arguments :

  • addrport: Optional port number, or a combination of ip address and port number (format is ipaddr:port).

Options :

  • -h, --help: Display help message and exit.

  • --ipv6, -6: Tells Django to use an IPv6 address. By default, it uses IPv4 addresses.

  • --nothreading: tells Django not to use threads. By default, Django uses threads to handle requests, which helps in parallel processing of multiple requests.

  • --noreload: Tells Django not to use auto-reloader. By default, Django automatically reloads the server when code changes so developers can see the latest changes.

  • --version: Display the program version number and exit.

  • --settings SETTINGS:Specify the Python path of a settings module, for example, "myproject.settings.main". If this option is not provided, DJANGO_SETTINGS_MODULEthe settings module specified in the environment variable will be used.

  • --pythonpath PYTHONPATH: Directory to add to the Python path. This allows you to specify additional directories so that the command can find relevant files for your project.

  • --no-color: Disable colorization of command output.

  • --force-color: Force colorization of command output.

  • --skip-checks: Skip system check. Use this option if you wish to ignore system checks and start the server immediately.

django-admin runserverThe command is typically used during development to start a development Web server. You can specify the port the server listens on by providing an optional port number, or you can use --ipv6the option to tell the server to use an IPv6 address. By default, the server uses threads to handle requests, and auto-reloading is enabled to refresh the server when code changes.

4.16 sendtestemail command

django-admin sendtestemailCommand is used to send a test email to the specified email address. Its syntax format is:

django-admin sendtestemail [-h] [--managers] [--admins] [--version] [-v {
    
    0,1,2,3}] [--settings SETTINGS]
                           [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--force-color]
                           [--skip-checks]
                           [email ...]

in:

Positional Arguments :

  • email: One or more email addresses to use for sending test emails.

Options :

  • -h, --help: Display help message and exit.

  • --managers: Send a test email to settings.MANAGERSthe email address specified in . settings.MANAGERSIs a list of email addresses used in Django projects to receive administrative alerts and error notifications.

  • --admins: Send a test email to settings.ADMINSthe email address specified in . settings.ADMINSAlso a list of email addresses used in Django projects to receive administrative alerts and error notifications.

  • --version: Display the program version number and exit.

  • -v {0,1,2,3}, --verbosity {0,1,2,3}: Set the output detail level of the command, which can be 0 (minimum output), 1 (normal output), 2 (verbose output), 3 (very detailed output).

  • --settings SETTINGS:Specify the Python path of a settings module, for example, "myproject.settings.main". If this option is not provided, DJANGO_SETTINGS_MODULEthe settings module specified in the environment variable will be used.

  • --pythonpath PYTHONPATH: Directory to add to the Python path. This allows you to specify additional directories so that the command can find relevant files for your project.

  • --traceback: CommandErrorThrows an exception when an exception occurs.

  • --no-color: Disable colorization of command output.

  • --force-color: Force colorization of command output.

  • --skip-checks: Skip system check. Use this option if you wish to ignore the system check and send a test email immediately.

django-admin sendtestemailThe command is typically used during development to test that a project's email settings are working properly, and to ensure that key personnel such as administrators and managers are receiving alert and error notification emails. You can specify an email address as a parameter or use the --managersand --adminsoptions to send a test email to a predefined email address.

4.17 shell commands

django-admin shellThe command starts the Python interactive interpreter, allowing you to interact with your Django project. Its syntax format is:

django-admin shell [-h] [--no-startup] [-i {
    
    ipython,bpython,python}] [-c COMMAND] [--version] [-v {
    
    0,1,2,3}]
                   [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color]
                   [--force-color]

in:

Options :

  • -h, --help: Display help message and exit.

  • --no-startup: When using the pure Python interactive interpreter, ignore the settings of PYTHONSTARTUPenvironment variables and ~/.pythonrc.pyscripts. This means that these startup scripts will not be executed.

  • -i {ipython,bpython,python}, --interface {ipython,bpython,python}: Specifies the interactive interpreter interface, available options include "ipython", "bpython" and "python". Django attempts to use one of these tools, if available, to provide a richer interactive experience.

  • -c COMMAND, --command COMMAND: Instead of opening an interactive shell, you can run a command as Django and exit after execution.

  • --version: Display the program version number and exit.

  • -v {0,1,2,3}, --verbosity {0,1,2,3}: Set the output detail level of the command, which can be 0 (minimum output), 1 (normal output), 2 (verbose output), 3 (very detailed output).

  • --settings SETTINGS:Specify the Python path of a settings module, for example, "myproject.settings.main". If this option is not provided, DJANGO_SETTINGS_MODULEthe settings module specified in the environment variable will be used.

  • --pythonpath PYTHONPATH: Directory to add to the Python path. This allows you to specify additional directories so that the command can find relevant files for your project.

  • --traceback: CommandErrorThrows an exception when an exception occurs.

  • --no-color: Disable colorization of command output.

  • --force-color: Force colorization of command output.

django-admin shellCommands are usually used during the development process to test code snippets, database queries, etc. of Django projects, as well as for interactive debugging and experiments. Different interfaces (such as IPython or bpython) can be used to increase interactivity.

4.18 showmigrations command

django-admin showmigrationsThis command displays information about all available migrations in the current project. Its syntax format is:

django-admin showmigrations [-h] [--database DATABASE] [--list | --plan] [--version] [-v {
    
    0,1,2,3}]
                            [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color]
                            [--force-color] [--skip-checks]
                            [app_label ...]

in:

Options :

  • -h, --help: Display help message and exit.

  • --database DATABASE: Specify the database to display migration information. The default is the "default" database.

  • --list, -l: Displays a list of all migrations and whether they have been applied. If verbosity level 2 or above is set, the date and time information when the migration was applied will also be included.

  • --plan, -p: Shows all migrations in the order they will be applied. If verbosity level 2 or above is set, all direct migration dependencies will also be included as well as reverse dependencies ( run_before).

  • --version: Display the program version number and exit.

  • -v {0,1,2,3}, --verbosity {0,1,2,3}: Set the output detail level of the command, which can be 0 (minimum output), 1 (normal output), 2 (verbose output), 3 (very detailed output).

  • --settings SETTINGS:Specify the Python path of a settings module, for example, "myproject.settings.main". If this option is not provided, DJANGO_SETTINGS_MODULEthe settings module specified in the environment variable will be used.

  • --pythonpath PYTHONPATH: Directory to add to the Python path. This allows you to specify additional directories so that the command can find relevant files for your project.

  • --traceback: CommandErrorThrows an exception when an exception occurs.

  • --no-color: Disable colorization of command output.

  • --force-color: Force colorization of command output.

django-admin showmigrationsThe command is useful for viewing migration information in a project and understanding which migrations have been applied to the database. It helps you manage migrations and ensures your database is in sync with your application's model definitions.

4.19 sqlflush command

django-admin sqlflushCommand is used to generate SQL statements to restore all tables in the database to their original post-installation state. Its syntax format is:

django-admin sqlflush [-h] [--database DATABASE] [--version] [-v {
    
    0,1,2,3}] [--settings SETTINGS]
                      [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--force-color] [--skip-checks]

in:

Options :

  • -h, --help: Display help message and exit.

  • --database DATABASE: Specify the database to generate SQL statements. The default is the "default" database.

  • --version: Display the program version number and exit.

  • -v {0,1,2,3}, --verbosity {0,1,2,3}: Set the output detail level of the command, which can be 0 (minimum output), 1 (normal output), 2 (verbose output), 3 (very detailed output).

  • --settings SETTINGS:Specify the Python path of a settings module, for example, "myproject.settings.main". If this option is not provided, DJANGO_SETTINGS_MODULEthe settings module specified in the environment variable will be used.

  • --pythonpath PYTHONPATH: Directory to add to the Python path. This allows you to specify additional directories so that the command can find relevant files for your project.

  • --traceback: CommandErrorThrows an exception when an exception occurs.

  • --no-color: Disable colorization of command output.

  • --force-color: Force colorization of command output.

django-admin sqlflushThe command is typically used to generate a set of SQL statements to reset all tables of the database to their initial post-installation state for testing or other needs. These SQL statements can be run in the database to delete all data and return the table's structure to its original state.

4.20 sqlmigrate command

django-admin sqlmigrateThe command is used to generate SQL statements for a specified migration to see how the migration will affect the database structure. Its syntax format is:

django-admin sqlmigrate [-h] [--database DATABASE] [--backwards] [--version] [-v {
    
    0,1,2,3}]
                        [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color]
                        [--force-color] [--skip-checks]
                        app_label migration_name

in:

Options :

  • -h, --help: Display help message and exit.

  • --database DATABASE: Specifies the database for which SQL statements are to be generated. The default is the "default" database.

  • --backwards:Create SQL to unapply the migration instead of applying it. If this option is specified, SQL statements are generated to restore the database from its current state to its pre-migration state.

  • --version: Display the program version number and exit.

  • -v {0,1,2,3}, --verbosity {0,1,2,3}: Set the output detail level of the command, which can be 0 (minimum output), 1 (normal output), 2 (verbose output), 3 (very detailed output).

  • --settings SETTINGS:Specify the Python path of a settings module, for example, "myproject.settings.main". If this option is not provided, DJANGO_SETTINGS_MODULEthe settings module specified in the environment variable will be used.

  • --pythonpath PYTHONPATH: Directory to add to the Python path. This allows you to specify additional directories so that the command can find relevant files for your project.

  • --traceback: CommandErrorThrows an exception when an exception occurs.

  • --no-color: Disable colorization of command output.

  • --force-color: Force colorization of command output.

django-admin sqlmigrateThe command is typically used to check the SQL statement that specifies a migration to ensure that the migration will be applied or unapplied to the database correctly. The generated SQL statements can be viewed as needed for debugging and analysis during development and maintenance.

4.21 sqlsequencereset command

django-admin sqlsequenceresetCommand is used to generate SQL statements that reset database sequences in a given application. Its syntax format is:

django-admin sqlsequencereset [-h] [--database DATABASE] [--version] [-v {
    
    0,1,2,3}] [--settings SETTINGS]
                              [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--force-color]
                              [--skip-checks]
                              app_label [app_label ...]

in:

Options :

  • -h, --help: Display help message and exit.

  • --database DATABASE: Specify the database to generate SQL statements. The default is the "default" database.

  • --version: Display the program version number and exit.

  • -v {0,1,2,3}, --verbosity {0,1,2,3}: Set the output detail level of the command, which can be 0 (minimum output), 1 (normal output), 2 (verbose output), 3 (very detailed output).

  • --settings SETTINGS:Specify the Python path of a settings module, for example, "myproject.settings.main". If this option is not provided, DJANGO_SETTINGS_MODULEthe settings module specified in the environment variable will be used.

  • --pythonpath PYTHONPATH: Directory to add to the Python path. This allows you to specify additional directories so that the command can find relevant files for your project.

  • --traceback: CommandErrorThrows an exception when an exception occurs.

  • --no-color: Disable colorization of command output.

  • --force-color: Force colorization of command output.

Positional Arguments :

  • app_label: One or more application labels (App Label). For these applications, SQL statements are generated to reset the sequence in the database. Sequences are used to generate unique identifiers such as primary keys. When you delete records and insert new records, the database needs to ensure the uniqueness of the primary key.

django-admin sqlsequenceresetThe command is typically used when you might insert data manually to ensure the correctness of the sequence. This helps you correctly assign unique identifiers in the database to avoid primary key conflicts.

4.22 squashmigrations command

django-admin squashmigrationsCommand is used to merge a set of existing migrations (starting from the first migration up to the specified migration) into a new migration. Its syntax format is:

django-admin squashmigrations [-h] [--no-optimize] [--noinput] [--squashed-name SQUASHED_NAME] [--no-header]
                              [--version] [-v {
    
    0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH]
                              [--traceback] [--no-color] [--force-color] [--skip-checks]
                              app_label [start_migration_name] migration_name

in:

Options :

  • -h, --help: Display help message and exit.

  • --no-optimize: No attempt is made to optimize the merge operation.

  • --noinput, --no-input: Tells Django not to prompt the user for any input.

  • --squashed-name SQUASHED_NAME: Set the name of the new merge migration. By default it will automatically generate a name based on the application name and migrated content.

  • --no-header: Do not add header comments for new merge migrations.

  • --version: Display the program version number and exit.

  • -v {0,1,2,3}, --verbosity {0,1,2,3}: Set the output detail level of the command, which can be 0 (minimum output), 1 (normal output), 2 (verbose output), 3 (very detailed output).

  • --settings SETTINGS:Specify the Python path of a settings module, for example, "myproject.settings.main". If this option is not provided, DJANGO_SETTINGS_MODULEthe settings module specified in the environment variable will be used.

  • --pythonpath PYTHONPATH: Directory to add to the Python path. This allows you to specify additional directories so that the command can find relevant files for your project.

  • --traceback: CommandErrorThrows an exception when an exception occurs.

  • --no-color: Disable colorization of command output.

  • --force-color: Force colorization of command output.

Positional Arguments :

  • app_label: The label of the application (App Label), indicating the application to be migrated and merged.

  • start_migration_name: Merge starting from this migration, including this migration. Indicates which migration to start merging from.

  • migration_name: Merge up to and including this migration. Represents the last migration to be merged.

django-admin squashmigrationscommand is typically used when you wish to combine multiple migrations into a larger migration. This can help simplify a project's migration history and reduce the number of database migration records.

4.23 startapp command

django-admin startappThe command is used to create a new Django application (App) and generate the application's directory structure and files. Its syntax format is:

django-admin startapp [-h] [--template TEMPLATE] [--extension EXTENSIONS] [--name FILES]
                      [--exclude [EXCLUDE]] [--version] [-v {
    
    0,1,2,3}] [--settings SETTINGS]
                      [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--force-color]
                      name [directory]

in:

Options :

  • -h, --help: Display help message and exit.

  • --template TEMPLATE: Specifies the path or URL from which to load the application template.

  • --extension EXTENSIONS, -e EXTENSIONS: Specify the file extension to render, default is "py" (Python file). You can specify multiple extensions separated by commas, or use -ethe option multiple times to add multiple extensions.

  • --name FILES, -n FILES: Specify the name of the file to be rendered, defaulting to the name of the application. You can specify multiple filenames separated by commas, or use -nthe option multiple times to add multiple filenames.

  • --exclude [EXCLUDE], -x [EXCLUDE]: Specify directory names to exclude, except .gitthe and __pycache__directories. You can use -xthe option multiple times to add multiple directories to exclude.

  • --version: Display the program version number and exit.

  • -v {0,1,2,3}, --verbosity {0,1,2,3}: Set the output detail level of the command, which can be 0 (minimum output), 1 (normal output), 2 (verbose output), 3 (very detailed output).

  • --settings SETTINGS:Specify the Python path of a settings module, for example, "myproject.settings.main". If this option is not provided, DJANGO_SETTINGS_MODULEthe settings module specified in the environment variable will be used.

  • --pythonpath PYTHONPATH: Directory to add to the Python path. This allows you to specify additional directories so that the command can find relevant files for your project.

  • --traceback: CommandErrorThrows an exception when an exception occurs.

  • --no-color: Disable colorization of command output.

  • --force-color: Force colorization of command output.

Positional Arguments :

  • name: The name of the application or project. You need to provide a name, which will become the name of the application you create.

  • directory: Optional target directory that specifies where the application will be created. If no directory is provided, the application will be created in the current directory.

django-admin startappThe command is typically used when you start a new Django application. It creates a skeleton application that contains the necessary files and directories so that you can add models, views, templates, and other application components to it.

4.24 startproject command

django-admin startprojectThe command is used to create a new Django project (Project) and generate the project's directory structure and files. Its syntax format is:

django-admin startproject [-h] [--template TEMPLATE] [--extension EXTENSIONS] [--name FILES]
                          [--exclude [EXCLUDE]] [--version] [-v {
    
    0,1,2,3}] [--settings SETTINGS]
                          [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--force-color]
                          name [directory]

in:

Options :

  • -h, --help: Display help message and exit.

  • --template TEMPLATE: Specify the path or URL from where to load the project template.

  • --extension EXTENSIONS, -e EXTENSIONS: Specify the file extension to render, default is "py" (Python file). You can specify multiple extensions separated by commas, or use -ethe option multiple times to add multiple extensions.

  • --name FILES, -n FILES: Specify the file name to be rendered, empty by default. You can specify multiple filenames separated by commas, or use -nthe option multiple times to add multiple filenames.

  • --exclude [EXCLUDE], -x [EXCLUDE]: Specify directory names to exclude, except .gitthe and __pycache__directories. You can use -xthe option multiple times to add multiple directories to exclude.

  • --version: Display the program version number and exit.

  • -v {0,1,2,3}, --verbosity {0,1,2,3}: Set the output detail level of the command, which can be 0 (minimum output), 1 (normal output), 2 (verbose output), 3 (very detailed output).

  • --settings SETTINGS:Specify the Python path of a settings module, for example, "myproject.settings.main". If this option is not provided, DJANGO_SETTINGS_MODULEthe settings module specified in the environment variable will be used.

  • --pythonpath PYTHONPATH: Directory to add to the Python path. This allows you to specify additional directories so that the command can find relevant files for your project.

  • --traceback: CommandErrorThrows an exception when an exception occurs.

  • --no-color: Disable colorization of command output.

  • --force-color: Force colorization of command output.

Positional Arguments :

  • name: The name of the project. You need to provide a name, which will become the name of the project you create.

  • directory: Optional target directory used to specify the location where the project is created. If no directory is provided, the project will be created in the current directory.

django-admin startprojectThe command is typically used when you start a new Django project. It creates an initial project skeleton that contains the project's directory structure and configuration files so that you can start developing your project.

4.25 testserver command

django-admin testserverThe command is used to run on the development server and load the specified data fixture (data snapshot) for testing or development purposes. Its syntax format is:

django-admin testserver [-h] [--noinput] [--addrport ADDRPORT] [--ipv6] [--version] [-v {
    
    0,1,2,3}]
                        [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color]
                        [--force-color]
                        [fixture ...]

in:

Options :

  • -h, --help: Display help message and exit.

  • --noinput, --no-input: Tells Django not to prompt the user to enter anything, but to run it automatically.

  • --addrport ADDRPORT: Specify the port number or the combination of IP address and port number where the server is running. For example, --addrport 8000or --addrport 0.0.0.0:8000.

  • --ipv6, -6: Tells Django to use an IPv6 address.

  • --version: Display the program version number and exit.

  • -v {0,1,2,3}, --verbosity {0,1,2,3}: Set the output detail level of the command, which can be 0 (minimum output), 1 (normal output), 2 (verbose output), 3 (very detailed output).

  • --settings SETTINGS:Specify the Python path of a settings module, for example, "myproject.settings.main". If this option is not provided, DJANGO_SETTINGS_MODULEthe settings module specified in the environment variable will be used.

  • --pythonpath PYTHONPATH: Directory to add to the Python path. This allows you to specify additional directories so that the command can find relevant files for your project.

  • --traceback: CommandErrorThrows an exception when an exception occurs.

  • --no-color: Disable colorization of command output.

  • --force-color: Force colorization of command output.

Positional Arguments :

  • fixture: The path to one or more data fixture files, used to load data to the development server. These fixtures can be pre-prepared data snapshots for use in a test or development environment.

django-admin testserverThe command is typically used to run the development server during testing or development and load test data for testing or use in development. This allows developers to simulate an environment with predefined data on the development server for testing and debugging purposes.

5. The relationship between app and project in Django

In the previous sections of this article, we introduced the creation of Django projects, as well as the startproject command and startapp command to create projects and create applications.

In Dajngo , project and application are different concepts. A project can contain one or more apps that together build the project's functionality. Applications are the components of a project that work together to build the overall functionality of the project. Applications are reusable and can be used in different projects. This helps modularize functionality and improve code maintainability.

5.1 Project

The project is the overall Django project. A project can contain one or more applications, as well as project-level configuration and settings files.

The project includes a set of applications and configures project-level settings such as the project's database connection, URL mapping, static file path, and template path.

Typically, a Django project represents a complete web application, containing multiple applications to build different functions.

A project has a project folder (usually the project name) that contains project-level configuration files (settings.py, etc.).

5.2 Application (App)

An application is a component of a Django project, which is a modular unit of a Django application.

Apps are often used to organize and manage the different functions and features of projects. Each application can contain models, views, templates, URL mappings, static files, etc.

The application is designed to make the code more modular, maintainable, and reusable in different projects. An application can be used in multiple projects.

Typically, an app handles a specific functional area, such as user authentication, blog posts, product catalogs, etc.

Guess you like

Origin blog.csdn.net/qq_28550263/article/details/132892113