### Verify Python Installation Source: https://docs.djangoproject.com/zh-hans/5.2/intro/install This code snippet demonstrates how to verify if Python is installed on your system by running the 'python' command in the shell. It shows the expected output format for a successful installation. ```shell python Python 3.x.y [GCC 4.x] on linux Type "help", "copyright", "credits" or "license" for more information. >>> ``` -------------------------------- ### Verify Django Installation Source: https://docs.djangoproject.com/zh-hans/5.2/intro/install This Python code snippet shows how to verify if Django is installed and accessible by importing it and printing its version. This is a crucial step after installing Django to ensure it's ready for use. ```python >>> import django >>> print(django.get_version()) 5.2 ``` -------------------------------- ### Django: Basic Test Example with Client Source: https://docs.djangoproject.com/zh-hans/5.2/topics/testing/tools Provides a basic example of how to use Django's test client to make a GET request, check the response status code, and verify the rendered context. It involves setting up a client and making assertions. ```python import unittest from django.test import Client class SimpleTest(unittest.TestCase): def setUp(self): # Every test needs a client. self.client = Client() def test_details(self): # Issue a GET request. response = self.client.get("/customer/details/") # Check that the response is 200 OK. self.assertEqual(response.status_code, 200) # Check that the rendered context contains 5 customers. self.assertEqual(len(response.context["customers"]), 5) ``` -------------------------------- ### Set Up Virtual Environment and Install Dependencies (Bash/Shell) Source: https://docs.djangoproject.com/zh-hans/5.2/internals/contributing/writing-documentation Creates a Python virtual environment, activates it, and installs the necessary dependencies for building Django documentation. This ensures a consistent development environment. ```shell python -m venv .venv source .venv/bin/activate python -m pip install -r docs/requirements.txt ``` -------------------------------- ### Migrate Data from Third-Party App in Django Source: https://docs.djangoproject.com/zh-hans/5.2/howto/writing-migrations This Python migration example demonstrates how to move data from a model in an 'old_app' to a 'new_app'. It includes error handling for when the 'old_app' is not installed using 'LookupError' and conditionally adds dependencies based on whether the 'old_app' is installed. This ensures the migration can be deployed even if the old app is not present. ```python from django.apps import apps as global_apps from django.db import migrations def forwards(apps, schema_editor): try: OldModel = apps.get_model("old_app", "OldModel") except LookupError: # The old app isn't installed. return NewModel = apps.get_model("new_app", "NewModel") NewModel.objects.bulk_create( NewModel(new_attribute=old_object.old_attribute) for old_object in OldModel.objects.all() ) class Migration(migrations.Migration): operations = [ migrations.RunPython(forwards, migrations.RunPython.noop), ] dependencies = [ ("myapp", "0123_the_previous_migration"), ("new_app", "0001_initial"), ] if global_apps.is_installed("old_app"): dependencies.append(("old_app", "0001_initial")) ``` -------------------------------- ### 配置 Django 测试环境 (Shell) Source: https://docs.djangoproject.com/zh-hans/5.2/intro/tutorial05 在 Django shell 中配置测试环境,使用 `setup_test_environment()` 来安装模板渲染器,这允许检查响应的额外属性,如 `response.context`。此方法不建立测试数据库,因此对现有数据库运行。 ```python >>> from django.test.utils import setup_test_environment >>> setup_test_environment() ``` -------------------------------- ### Django Setup Process Source: https://docs.djangoproject.com/zh-hans/5.2/ref/applications Details the `django.setup()` function and the three-stage application loading process. ```APIDOC ## Initialization Process ### `django.setup(_set_prefix=True_)` **Description**: Configures Django, including loading settings, setting up logging, prefixing script names if `set_prefix` is `True`, and initializing the application registry. Automatically called by Django's HTTP services and management commands. Must be called explicitly in other contexts (e.g., standalone Python scripts). **Method**: N/A (Function) **Parameters**: * `_set_prefix_` (bool) - Optional - If `True`, prefixes script names with `FORCE_SCRIPT_NAME`. Defaults to `True`. ### Application Loading Stages Django's application registry initialization occurs in three stages, processing apps in the order they appear in `INSTALLED_APPS`: 1. **Import App Roots**: Django imports the root package of each app or its `apps.py` module. Apps configured via `AppConfig` are loaded. **Crucially, no models should be imported during this stage, directly or indirectly.** After this stage, you can use APIs like `get_app_config()`. 2. **Import Models**: Django attempts to import the `models` submodule of each application. All models must be defined or imported within `models.py` or `models/__init__.py`. After this stage, model-related APIs like `get_model()` become fully functional. 3. **Run `ready()` Methods**: Django calls the `ready()` method for each application's `AppConfig`. This is where initialization tasks like signal registration should occur. ``` -------------------------------- ### Homebrew Installation Summary for GeoDjango Prerequisites (macOS) Source: https://docs.djangoproject.com/zh-hans/5.2/ref/contrib/gis/install A summary of Homebrew commands to install necessary geospatial prerequisites for GeoDjango on macOS. Homebrew is a package manager that simplifies the installation of software from source on macOS. ```bash $ brew install postgresql $ brew install postgis $ brew install gdal $ brew install libgeoip ``` -------------------------------- ### Create Django Project Source: https://docs.djangoproject.com/zh-hans/5.2/intro/tutorial01 Initializes a new Django project with the specified project name ('mysite') and a root directory ('djangotutorial'). This command sets up the basic file structure and configuration for a Django project. ```shell $ django-admin startproject mysite djangotutorial ``` ```shell ...\> django-admin startproject mysite djangotutorial ``` -------------------------------- ### Configuring System Library Path (GNU/Linux) Source: https://docs.djangoproject.com/zh-hans/5.2/ref/contrib/gis/install This example demonstrates how to update the system's library path on GNU/Linux systems. It involves adding a custom library path (e.g., /usr/local/lib) to the ldconfig configuration and then running ldconfig to update the system's library cache. This ensures that system-wide libraries are discoverable. ```bash $ sudo echo /usr/local/lib >> /etc/ld.so.conf $ sudo ldconfig ``` -------------------------------- ### 运行 Django 开发服务器 Source: https://docs.djangoproject.com/zh-hans/5.2/intro/tutorial01 使用 manage.py 运行 Django 的内置开发服务器,以测试应用程序。 ```Shell $ python manage.py runserver ``` ```Shell ...pe manage.py runserver ``` -------------------------------- ### Get Homebrew Installation Prefix Source: https://docs.djangoproject.com/zh-hans/5.2/ref/contrib/gis/install/spatialite Retrieves the base installation path for Homebrew packages on macOS. This path is needed to construct the full path to the SpatiaLite library for GeoDjango configuration. ```bash $ brew --prefix /opt/homebrew ``` -------------------------------- ### Install psycopg Python Module Source: https://docs.djangoproject.com/zh-hans/5.2/ref/contrib/gis/install Installs the psycopg Python module, which provides an interface between Python and PostgreSQL databases. This command is typically run within a Python virtual environment using pip. ```bash ...\> py -m pip install psycopg ``` -------------------------------- ### Django 运行 migrate 命令 Source: https://docs.djangoproject.com/zh-hans/5.2/ref/contrib/gis/tutorial 用于在 Django 项目中创建数据库迁移和应用这些迁移。首先使用 `makemigrations` 生成迁移文件,然后 `sqlmigrate` 查看 SQL 语句,最后 `migrate` 将更改应用到数据库。适用于命令行操作。 ```shell $ python manage.py makemigrations Migrations for 'world': world/migrations/0001_initial.py: + Create model WorldBorder ``` ```shell ...\> py manage.py makemigrations Migrations for 'world': world/migrations/0001_initial.py: + Create model WorldBorder ``` ```shell $ python manage.py sqlmigrate world 0001 ``` ```shell ...\> py manage.py sqlmigrate world 0001 ``` ```sql BEGIN; -- -- Create model WorldBorder -- CREATE TABLE "world_worldborder" ( "id" bigint NOT NULL PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY, "name" varchar(50) NOT NULL, "area" integer NOT NULL, "pop2005" integer NOT NULL, "fips" varchar(2) NOT NULL, "iso2" varchar(2) NOT NULL, "iso3" varchar(3) NOT NULL, "un" integer NOT NULL, "region" integer NOT NULL, "subregion" integer NOT NULL, "lon" double precision NOT NULL, "lat" double precision NOT NULL "mpoly" geometry(MULTIPOLYGON,4326) NOT NULL ) ; CREATE INDEX "world_worldborder_mpoly_id" ON "world_worldborder" USING GIST ("mpoly"); COMMIT; ``` ```shell $ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, world Running migrations: ... Applying world.0001_initial... OK ``` ```shell ...\> py manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, world Running migrations: ... Applying world.0001_initial... OK ``` -------------------------------- ### MacPorts Installation Summary for GeoDjango Prerequisites (macOS) Source: https://docs.djangoproject.com/zh-hans/5.2/ref/contrib/gis/install A summary of MacPorts commands to install GeoDjango's geospatial prerequisites on macOS. MacPorts is another package manager for macOS that compiles software from source. ```bash $ sudo port install postgresql14-server $ sudo port install geos $ sudo port install proj6 $ sudo port install postgis3 $ sudo port install gdal $ sudo port install libgeoip ``` -------------------------------- ### 安全调用 django.setup() 的条件执行 Source: https://docs.djangoproject.com/zh-hans/5.2/topics/settings 此代码片段演示了如何将 `django.setup()` 调用放在 `if __name__ == '__main__':` 块中。这确保了 `django.setup()` 只在脚本作为主程序直接运行时执行,而不是在被导入时执行,避免了不必要的配置。 ```python if __name__ == "__main__": import django django.setup() ``` -------------------------------- ### 运行 Django 特定目录测试 Source: https://docs.djangoproject.com/zh-hans/5.2/intro/contributing 此命令用于运行 Django 测试套件中特定目录下的测试。在本例中,它运行 `shortcuts` 目录中的所有测试。这对于在进行更改后隔离和验证特定功能的测试非常有用。 ```bash $ ./runtests.py shortcuts ``` ```batch ...\> runtests.py shortcuts ``` -------------------------------- ### Django Pre Migrate Signal Example Source: https://docs.djangoproject.com/zh-hans/5.2/ref/signals The pre_migrate signal is emitted by the migrate command before it starts applying migrations. It's useful for performing checks or setup tasks before database schema changes occur. The signal passes arguments like sender, app_config, verbosity, interactive, stdout, using, plan, and apps. ```python from django.db.models.signals import pre_migrate def pre_migrate_handler(sender, **kwargs): print(f"Pre-migrate signal received for app: {sender.label}") # Perform pre-migration tasks here # You can access the migration plan via kwargs.get('plan') pass # To connect this signal, you might do it in your AppConfig's ready method # Or in a signals.py file imported by your AppConfig. # Example connection (assuming you have an AppConfig): # from django.apps import AppConfig # class MyAppConfig(AppConfig): # name = 'myapp' # def ready(self): # pre_migrate.connect(pre_migrate_handler, sender=self) ``` -------------------------------- ### Start uWSGI server for Django (command line) Source: https://docs.djangoproject.com/zh-hans/5.2/howto/deployment/wsgi/uwsgi Starts the uWSGI server for a Django project using command-line arguments. It specifies project directory, WSGI module, settings module, master process, PID file, socket, number of worker processes, user/group IDs, request timeouts, and logging. ```bash uwsgi --chdir=/path/to/your/project \ --module=mysite.wsgi:application \ --env DJANGO_SETTINGS_MODULE=mysite.settings \ --master --pidfile=/tmp/project-master.pid \ --socket=127.0.0.1:49152 \ --processes=5 \ --uid=1000 --gid=2000 \ --harakiri=20 \ --max-requests=5000 \ --vacuum \ --home=/path/to/virtual/env \ --daemonize=/var/log/uwsgi/yourproject.log ``` -------------------------------- ### Build and Install GEOS from Source (Bash) Source: https://docs.djangoproject.com/zh-hans/5.2/ref/contrib/gis/install/geolibs Guides through downloading, building, and installing the GEOS library from source. It involves downloading the source, configuring with CMake, building, and installing the library. This is necessary if GeoDjango cannot find the GEOS library. ```bash wget https://download.osgeo.org/geos/geos-X.Y.Z.tar.bz2 tar xjf geos-X.Y.Z.tar.bz2 cd geos-X.Y.Z mkdir build cd build cmake -DCMAKE_BUILD_TYPE=Release .. cmake --build . sudo cmake --build . --target install ``` -------------------------------- ### Django ASGI Application Object Configuration Source: https://docs.djangoproject.com/zh-hans/5.2/howto/deployment/asgi The `application` object is a callable that ASGI servers use to interact with your Django code. The `startproject` command generates `/asgi.py` containing this object. It's used by ASGI servers, not the development server. ```python import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') application = get_asgi_application() ``` -------------------------------- ### Installing binutils on Red Hat/CentOS Source: https://docs.djangoproject.com/zh-hans/5.2/ref/contrib/gis/install Command to install the 'binutils' package on Red Hat and CentOS-based Linux distributions. Binutils is required for GeoDjango's library discovery mechanism, which uses 'objdump' to validate shared libraries. ```bash $ sudo yum install binutils ``` -------------------------------- ### 导入和实例化 Django Client Source: https://docs.djangoproject.com/zh-hans/5.2/intro/tutorial05 导入 `django.test.Client` 类并创建一个实例,以便在 shell 中模拟用户与视图层的交互。这个步骤在 `tests.py` 中使用 `django.test.TestCase` 时不是必需的,因为 TestCase 自带一个客户端。 ```python >>> from django.test import Client >>> client = Client() ``` -------------------------------- ### Installing binutils on Debian/Ubuntu Source: https://docs.djangoproject.com/zh-hans/5.2/ref/contrib/gis/install Command to install the 'binutils' package on Debian and Ubuntu-based Linux distributions. Binutils is required because GeoDjango uses the 'find_library' function, which relies on the 'objdump' program from binutils to verify shared libraries on GNU/Linux systems. ```bash $ sudo apt-get install binutils ``` -------------------------------- ### ldconfig Command Example (Bash) Source: https://docs.djangoproject.com/zh-hans/5.2/ref/contrib/gis/install/geolibs Demonstrates running the `ldconfig` command after installing a library from source on Linux. This command updates the shared library cache, ensuring that newly installed libraries are discoverable by the system. ```bash sudo make install sudo ldconfig ``` -------------------------------- ### Django TEMPLATES Configuration Example Source: https://docs.djangoproject.com/zh-hans/5.2/topics/templates Provides a sample configuration for Django's TEMPLATES setting in settings.py. This example sets up the DjangoTemplates backend, enables app directory searching, and includes a placeholder for backend-specific options. ```python TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True, "OPTIONS": { # ... some options here ... }, }, ] ``` -------------------------------- ### Setting PATH for Postgres.app on macOS Source: https://docs.djangoproject.com/zh-hans/5.2/ref/contrib/gis/install Instructions for adding the Postgres.app binary directory to the PATH environment variable in the .bash_profile on macOS. This allows command-line tools from the installed Postgres.app (including PostGIS) to be accessible. ```bash export PATH=$PATH:/Applications/Postgres.app/Contents/Versions/X.Y/bin ``` -------------------------------- ### Modifying PATH for Python Framework on macOS Source: https://docs.djangoproject.com/zh-hans/5.2/ref/contrib/gis/install This snippet shows how to update the PATH environment variable in the .profile file on macOS. It's used to ensure that the system uses a newer version of Python installed from the Python Software Foundation's framework installer, rather than the system-provided Python. ```bash export PATH=/Library/Frameworks/Python.framework/Versions/Current/bin:$PATH ``` -------------------------------- ### 运行 Django 应用测试 (Shell) Source: https://docs.djangoproject.com/zh-hans/5.2/intro/tutorial05 使用 Django 的 manage.py 脚本来运行指定应用的测试。这通常用于验证模型或视图的逻辑是否按预期工作。执行此命令会创建一个临时的测试数据库,运行所有以 'test_' 开头的方法,然后销毁测试数据库。 ```bash $ python manage.py test polls ``` ```powershell ...\> py manage.py test polls ``` -------------------------------- ### Django DateTimeRangeField usage Source: https://docs.djangoproject.com/zh-hans/5.2/ref/contrib/postgres/fields This example showcases the DateTimeRangeField in Django, used here within an Event model to store event start times. It illustrates creating an Event object with a specific start timestamp. ```python from django.db import models from django.utils import timezone class Event(models.Model): name = models.CharField(max_length=200) ages = IntegerRangeField() # Assuming IntegerRangeField is also present start = models.DateTimeField() def __str__(self): return self.name ``` ```python >>> import datetime >>> from django.utils import timezone >>> now = timezone.now() >>> Event.objects.create(name="Soft play", ages=(0, 10), start=now) ``` -------------------------------- ### 独立 Django 应用配置与设置 Source: https://docs.djangoproject.com/zh-hans/5.2/topics/settings 此代码片段展示了如何在独立 Python 脚本中配置 Django 设置并调用 `django.setup()`。这允许脚本访问 Django 的 ORM 和其他组件。确保仅在真正独立的情况下调用 `django.setup()`。 ```python import django from django.conf import settings from myapp import myapp_defaults settings.configure(default_settings=myapp_defaults, DEBUG=True) django.setup() # Now this script or any imported module can use any part of Django it needs. from myapp import models ``` -------------------------------- ### WeekMixin: Get Week Information Source: https://docs.djangoproject.com/zh-hans/5.2/ref/class-based-views/mixins-date-based The WeekMixin is designed for retrieving and parsing the week component of dates. It utilizes strftime() for week formatting, with options for week starting on Sunday ('%U'), Monday ('%W'), or ISO 8601 ('%V'). The week value can be sourced from attributes, URL parameters, or GET parameters. It also offers methods to calculate the start of the next and previous weeks. ```python class WeekMixin: week_format = '%U' # Default: week starts on Sunday week = None def get_week_format(self): return self.week_format def get_week(self): # Logic to get week from self.week, URL, or GET parameters pass def get_next_week(self, date_obj): # Logic to get the first day of the next week pass def get_prev_week(self, date_obj): # Logic to get the first day of the previous week pass ``` -------------------------------- ### Build Documentation Locally (Windows Command Prompt) Source: https://docs.djangoproject.com/zh-hans/5.2/internals/contributing/writing-documentation Navigates to the 'docs' directory and builds the HTML documentation locally using 'make.bat html'. This is the Windows equivalent of building the documentation. ```batch cd docs make.bat html ``` -------------------------------- ### Django 测试:make_toast 函数 Source: https://docs.djangoproject.com/zh-hans/5.2/intro/contributing 为 Django 添加新功能时,编写测试用例是必需的。此 Python 代码创建了一个名为 `MakeToastTests` 的测试类,其中包含一个 `test_make_toast` 方法。此测试旨在验证 `django.shortcuts.make_toast()` 函数是否按预期返回字符串 'toast'。 ```python from django.shortcuts import make_toast from django.test import SimpleTestCase class MakeToastTests(SimpleTestCase): def test_make_toast(self): self.assertEqual(make_toast(), "toast") ``` -------------------------------- ### Get GML Representation of OGRGeometry - Python Source: https://docs.djangoproject.com/zh-hans/5.2/ref/contrib/gis/gdal This example shows how to get the Geography Markup Language (GML) string representation of an OGRGeometry object. The `gml` property returns this formatted string, which is useful for interoperability with other systems that use GML. ```python >>> OGRGeometry("POINT(1 2)").gml '1,2' ``` -------------------------------- ### Django TestCase setUpTestData Example Source: https://docs.djangoproject.com/zh-hans/5.2/topics/testing/tools Illustrates the use of the setUpTestData class method in Django's TestCase for setting up initial data once for the entire test class, leading to faster test execution compared to using setUp(). Data defined here must be deep-copyable. ```python from django.test import TestCase from .models import Foo class MyTests(TestCase): @classmethod def setUpTestData(cls): # Set up data for the whole TestCase cls.foo = Foo.objects.create(bar="Test") def test1(self): # Some test using self.foo pass def test2(self): # Some other test using self.foo pass ``` -------------------------------- ### Get JSON Representation of OGRGeometry - Python Source: https://docs.djangoproject.com/zh-hans/5.2/ref/contrib/gis/gdal This example shows how to get the JavaScript Object Notation (JSON) string representation of an OGRGeometry object. The `json` property returns this format, which is commonly used in web applications and APIs for geospatial data. ```python >>> OGRGeometry("POINT(1 2)").json '{ "type": "Point", "coordinates": [ 1.000000, 2.000000 ] }' ``` -------------------------------- ### Install Django in Editable Mode Source: https://docs.djangoproject.com/zh-hans/5.2/intro/contributing This command installs the cloned Django copy into your activated virtual environment in 'editable' mode. This means any changes you make to the source code will be immediately reflected, which is crucial for testing your contributions. ```bash $ python -m pip install -e /path/to/your/local/clone/django/ ``` ```batch ...\> py -m pip install -e \path\to\your\local\clone\django\ ``` -------------------------------- ### Configuring PATH and DYLD_FALLBACK_LIBRARY_PATH for MacPorts (macOS) Source: https://docs.djangoproject.com/zh-hans/5.2/ref/contrib/gis/install This snippet illustrates how to configure the PATH and DYLD_FALLBACK_LIBRARY_PATH environment variables in the .profile file on macOS when using MacPorts. These settings ensure that command-line tools and libraries installed via MacPorts are accessible to the system and Python. ```bash export PATH=/opt/local/bin:/opt/local/lib/postgresql14/bin export DYLD_FALLBACK_LIBRARY_PATH=/opt/local/lib:/opt/local/lib/postgresql14 ``` -------------------------------- ### Django: 组合 DetailView 和 FormMixin 处理表单 Source: https://docs.djangoproject.com/zh-hans/5.2/topics/class-based-views/mixins 展示如何组合 DetailView 和 FormMixin 来处理 GET 请求显示作者详情和 POST 请求提交表单。此方法不推荐,因为它增加了复杂性。需要注意 FormMixin 的 post() 实现。 ```python # CAUTION: you almost certainly do not want to do this. # It is provided as part of a discussion of problems you can # run into when combining different generic class-based view # functionality that is not designed to be used together. from django import forms from django.http import HttpResponseForbidden from django.urls import reverse from django.views.generic import DetailView from django.views.generic.edit import FormMixin from books.models import Author class AuthorInterestForm(forms.Form): message = forms.CharField() class AuthorDetailView(FormMixin, DetailView): model = Author form_class = AuthorInterestForm def get_success_url(self): return reverse("author-detail", kwargs={"pk": self.object.pk}) def post(self, request, *args, **kwargs): if not request.user.is_authenticated: return HttpResponseForbidden() self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): # Here, we would record the user's interest using the message # passed in form.cleaned_data['message'] return super().form_valid(form) ``` -------------------------------- ### Django 视图处理 404 错误 (Python) Source: https://docs.djangoproject.com/zh-hans/5.2/intro/tutorial03 此 Python 代码演示了如何在 Django 视图中处理可能不存在的对象。它尝试使用 `Question.objects.get()` 获取一个 `Question` 对象,如果对象不存在(`Question.DoesNotExist`),则抛出 `Http404` 异常,通知用户该资源不存在。最后,使用 `render()` 函数渲染详情模板。 ```python from django.http import Http404 from django.shortcuts import render from .models import Question # ... def detail(request, question_id): try: question = Question.objects.get(pk=question_id) except Question.DoesNotExist: raise Http404("Question does not exist") return render(request, "polls/detail.html", {"question": question}) ``` -------------------------------- ### Django Database Configuration - SQLite Example Source: https://docs.djangoproject.com/zh-hans/5.2/ref/settings Configures a default SQLite database connection. This is the simplest setup, requiring only the database name (file path). ```python DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": "mydatabase.db", } } ``` -------------------------------- ### Django TestCase setUpClass Example Source: https://docs.djangoproject.com/zh-hans/5.2/topics/testing/tools Demonstrates how to correctly override setUpClass and tearDownClass in a Django TestCase, ensuring super() methods are called to maintain proper class-level initialization and cleanup, especially when dealing with configuration overrides. ```python from django.test import TestCase class MyTestCase(TestCase): @classmethod def setUpClass(cls): super().setUpClass() # ... your class setup code ... @classmethod def tearDownClass(cls): # ... your class teardown code ... super().tearDownClass() ``` -------------------------------- ### Count and Distinct Counts for Reporters by Article Fields (Django ORM) Source: https://docs.djangoproject.com/zh-hans/5.2/topics/db/examples/many_to_one This example demonstrates how to count 'Reporter' objects based on related 'Article' fields, and how to use `.distinct()` to get a unique count. ```python Reporter.objects.filter(article__headline__startswith="This").count() Reporter.objects.filter(article__headline__startswith="This").distinct().count() ``` -------------------------------- ### Retrieving BoundField Initial Values in Django Source: https://docs.djangoproject.com/zh-hans/5.2/ref/forms/api Explains how to get the initial data for a BoundField. It prioritizes 'Form.initial' and then 'Field.initial'. The example shows that initial values, especially callables, are cached. ```python >>> from datetime import datetime >>> class DatedCommentForm(CommentForm): ... created = forms.DateTimeField(initial=datetime.now) ... >>> f = DatedCommentForm() >>> f["created"].initial datetime.datetime(2021, 7, 27, 9, 5, 54) >>> f["created"].initial datetime.datetime(2021, 7, 27, 9, 5, 54) ``` -------------------------------- ### 包含静态和模板文件的 MANIFEST.in Source: https://docs.djangoproject.com/zh-hans/5.2/intro/reusable-apps 此 `MANIFEST.in` 文件指定了在构建 Python 包时应包含的额外非 Python 文件。在此示例中,它指示包含 `django_polls` 目录下的所有 `static` 和 `templates` 文件,这对于 Django 应用是必需的。 ```text recursive-include django_polls/static * recursive-include django_polls/templates * ```