### Start uWSGI server via command line Source: https://docs.djangoproject.com/en/5.2/howto/deployment/wsgi/uwsgi Example command to launch the uWSGI server with common configuration options for a Django project. ```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 \ # can also be a file --processes=5 \ # number of worker processes --uid=1000 --gid=2000 \ # if root, uwsgi can drop privileges --harakiri=20 \ # respawn processes taking more than 20 seconds --max-requests=5000 \ # respawn processes after serving 5000 requests --vacuum \ # clear environment on exit --home=/path/to/virtual/env \ # optional path to a virtual environment --daemonize=/var/log/uwsgi/yourproject.log # background the process ``` -------------------------------- ### setup_test_environment(debug=None) Source: https://docs.djangoproject.com/en/5.2/topics/testing/advanced Performs global pre-test setup, such as installing instrumentation for the template rendering system and setting up the dummy email outbox. ```APIDOC ## setup_test_environment(debug=None) ### Description Performs global pre-test setup, such as installing instrumentation for the template rendering system and setting up the dummy email outbox. If debug is provided, the DEBUG setting is updated to its value. ### Parameters - **debug** (bool) - Optional - The value to set for the DEBUG setting. ``` -------------------------------- ### Build and install PROJ Source: https://docs.djangoproject.com/en/5.2/ref/contrib/gis/install/geolibs Compile and install PROJ using CMake. ```bash $ cmake .. $ cmake --build . $ sudo cmake --build . --target install ``` -------------------------------- ### User input examples Source: https://docs.djangoproject.com/en/5.2/intro/tutorial02 Examples of terminal prompts for username, email, and password during superuser creation. ```text Username: admin ``` ```text Email address: admin@example.com ``` ```text Password: ********** Password (again): ********* Superuser created successfully. ``` -------------------------------- ### Build and install libspatialite Source: https://docs.djangoproject.com/en/5.2/ref/contrib/gis/install/spatialite Standard commands to download, configure, and install the SpatiaLite library from source. ```bash $ wget https://www.gaia-gis.it/gaia-sins/libspatialite-sources/libspatialite-X.Y.Z.tar.gz $ tar xaf libspatialite-X.Y.Z.tar.gz $ cd libspatialite-X.Y.Z $ ./configure $ make $ sudo make install ``` -------------------------------- ### Install and run tox Source: https://docs.djangoproject.com/en/5.2/internals/contributing/writing-code/unit-tests Commands to install tox and execute the default test suite. ```bash $ python -m pip install tox $ tox ``` ```bash ...\> py -m pip install tox ...\> tox ``` -------------------------------- ### Install Sphinx Source: https://docs.djangoproject.com/en/5.2/intro/whatsnext Install the Sphinx documentation generator using pip. ```bash $ python -m pip install Sphinx ``` ```batch ...\> py -m pip install Sphinx ``` -------------------------------- ### Install and Run aiosmtpd for Local Email Testing Source: https://docs.djangoproject.com/en/5.2/topics/email Use these commands to install the aiosmtpd package and start a local SMTP server on port 8025 that prints email output to the terminal. ```bash python -m pip install aiosmtpd python -m aiosmtpd -n -l localhost:8025 ``` -------------------------------- ### Install pre-commit hooks Source: https://docs.djangoproject.com/en/5.2/internals/contributing/writing-code/coding-style Commands to install the pre-commit framework and initialize git hooks for local development. ```bash $ python -m pip install pre-commit $ pre-commit install ``` ```powershell ...\> py -m pip install pre-commit ...\> pre-commit install ``` -------------------------------- ### Install build tools Source: https://docs.djangoproject.com/en/5.2/internals/howto-release-django Install the required Python packages for building release artifacts. ```bash $ python -m pip install build twine ``` -------------------------------- ### Install Hypercorn Source: https://docs.djangoproject.com/en/5.2/howto/deployment/asgi/hypercorn Use pip to install the Hypercorn package in your environment. ```bash python -m pip install hypercorn ``` -------------------------------- ### Define Django VERSION tuple examples Source: https://docs.djangoproject.com/en/5.2/internals/howto-release-django Examples of how the VERSION tuple maps to displayed version strings. ```python (4, 1, 1, "final", 0) ``` ```python (4, 2, 0, "alpha", 0) ``` ```python (4, 2, 0, "beta", 1) ``` -------------------------------- ### Install Package as User Library Source: https://docs.djangoproject.com/en/5.2/intro/reusable-apps Use pip to install the built distribution file as a per-user library. ```bash python -m pip install --user django-polls/dist/django_polls-0.1.tar.gz ``` -------------------------------- ### Perform an asynchronous GET request Source: https://docs.djangoproject.com/en/5.2/topics/testing/tools Demonstrates how to initialize the AsyncClient and perform a GET request with custom headers. ```python >>> c = AsyncClient() >>> c.get("/customers/details/", {"name": "fred", "age": 7}, ACCEPT="application/json") ``` -------------------------------- ### Comprehensive permission check example Source: https://docs.djangoproject.com/en/5.2/topics/auth/default A complete example demonstrating nested permission checks for an application. ```django {% if perms.foo %}

You have permission to do something in the foo app.

{% if perms.foo.add_vote %}

You can vote!

{% endif %} {% if perms.foo.add_driving %}

You can drive!

{% endif %} {% else %}

You don't have permission to do anything in the foo app.

{% endif %} ``` -------------------------------- ### Install ReportLab Source: https://docs.djangoproject.com/en/5.2/howto/outputting-pdf Commands to install the ReportLab library via pip on different operating systems. ```bash $ python -m pip install reportlab ``` ```bash ...\> py -m pip install reportlab ``` -------------------------------- ### Install GeoDjango Prerequisites via Homebrew Source: https://docs.djangoproject.com/en/5.2/ref/contrib/gis/install Use Homebrew to install PostgreSQL, PostGIS, GDAL, and libgeoip. ```bash $ brew install postgresql $ brew install postgis $ brew install gdal $ brew install libgeoip ``` -------------------------------- ### Install Uvicorn and Gunicorn Source: https://docs.djangoproject.com/en/5.2/howto/deployment/asgi/uvicorn Install necessary packages for production deployment using Gunicorn with Uvicorn workers. ```bash python -m pip install uvicorn uvicorn-worker gunicorn ``` -------------------------------- ### Install Django in editable mode Source: https://docs.djangoproject.com/en/5.2/intro/contributing Install the local clone of Django in editable mode so that changes are immediately reflected. ```bash $ python -m pip install -e /path/to/your/local/clone/django/ ``` ```batch ...\> py -m pip install -e \path\to\your\local\clone\django\ ``` -------------------------------- ### Install Django Source: https://docs.djangoproject.com/en/5.2/howto/windows Use pip to install the latest Django release within an active virtual environment. ```bash ...\> py -m pip install Django ``` -------------------------------- ### Set up virtual environment and dependencies Source: https://docs.djangoproject.com/en/5.2/internals/contributing/writing-documentation Create a virtual environment and install the necessary documentation dependencies. ```bash $ python -m venv .venv $ source .venv/bin/activate $ python -m pip install -r docs/requirements.txt ``` -------------------------------- ### pre_migrate Source: https://docs.djangoproject.com/en/5.2/ref/signals Sent by the migrate command before it starts to install an application. ```APIDOC ## pre_migrate ### Description Sent by the `migrate` command before it starts to install an application. It is not emitted for applications that lack a `models` module. ### Arguments - **sender** (AppConfig) - The AppConfig instance for the application about to be migrated. - **app_config** (AppConfig) - Same as sender. - **verbosity** (int) - Indicates how much information is printed on screen. - **interactive** (bool) - If True, it is safe to prompt the user for input. - **stdout** (object) - A stream-like object for verbose output. - **using** (str) - The alias of the database on which the command operates. - **plan** (list) - The migration plan used for the run. - **apps** (Apps) - An instance of Apps containing the state of the project before the migration. ``` -------------------------------- ### Retrieve objects using get() Source: https://docs.djangoproject.com/en/5.2/ref/models/querysets Examples of retrieving single objects and handling common exceptions. ```python Entry.objects.get(id=1) Entry.objects.get(Q(blog=blog) & Q(entry_number=1)) ``` ```python Entry.objects.filter(pk=1).get() ``` ```python Entry.objects.get(id=-999) # raises Entry.DoesNotExist ``` ```python Entry.objects.get(name="A Duplicated Name") # raises Entry.MultipleObjectsReturned ``` ```python from django.core.exceptions import ObjectDoesNotExist try: blog = Blog.objects.get(id=1) entry = Entry.objects.get(blog=blog, entry_number=1) except ObjectDoesNotExist: print("Either the blog or entry doesn't exist.") ``` -------------------------------- ### setup_databases(verbosity, interactive, *, time_keeper=None, keepdb=False, debug_sql=False, parallel=0, aliases=None, serialized_aliases=None, **kwargs) Source: https://docs.djangoproject.com/en/5.2/topics/testing/advanced Creates the test databases and returns a data structure required for teardown. ```APIDOC ## setup_databases(...) ### Description Creates the test databases. Returns a data structure that provides enough detail to undo the changes that have been made, which is required for the teardown_databases() function. ### Parameters - **verbosity** (int) - Required - **interactive** (bool) - Required - **time_keeper** (object) - Optional - **keepdb** (bool) - Optional - Defaults to False - **debug_sql** (bool) - Optional - Defaults to False - **parallel** (int) - Optional - Defaults to 0 - **aliases** (list) - Optional - Determines which DATABASES aliases test databases should be set up for. - **serialized_aliases** (list) - Optional - Determines what subset of aliases test databases should have their state serialized. ``` -------------------------------- ### Install the query logger Source: https://docs.djangoproject.com/en/5.2/topics/db/instrumentation Shows how to instantiate and apply the QueryLogger class within a context manager. ```python from django.db import connection ql = QueryLogger() with connection.execute_wrapper(ql): do_queries() # Now we can print the log. print(ql.queries) ``` -------------------------------- ### Example template search configuration Source: https://docs.djangoproject.com/en/5.2/topics/templates Demonstrates how multiple engines and directories are ordered for template resolution. ```python TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [ "/home/html/example.com", "/home/html/default", ], }, { "BACKEND": "django.template.backends.jinja2.Jinja2", "DIRS": [ "/home/html/jinja2", ], }, ] ``` -------------------------------- ### Get single field value with values_list() and get() Source: https://docs.djangoproject.com/en/5.2/ref/models/querysets Combine values_list() with get() to retrieve a specific field value for a single model instance. ```python >>> Entry.objects.values_list("headline", flat=True).get(pk=1) 'First entry' ``` -------------------------------- ### Bootstrap a new Django project Source: https://docs.djangoproject.com/en/5.2/intro/tutorial01 Initialize the Django project structure within the created directory. ```bash $ django-admin startproject mysite djangotutorial ``` ```batch ...\> django-admin startproject mysite djangotutorial ``` -------------------------------- ### Install Uvicorn Source: https://docs.djangoproject.com/en/5.2/howto/deployment/asgi/uvicorn Install the Uvicorn package using pip. ```bash python -m pip install uvicorn ``` -------------------------------- ### Install Daphne Source: https://docs.djangoproject.com/en/5.2/howto/deployment/asgi/daphne Use pip to install the Daphne package. ```bash python -m pip install daphne ``` -------------------------------- ### Accessing storage backends and creating instances Source: https://docs.djangoproject.com/en/5.2/ref/files/storage Demonstrates how to inspect configured storage backends and manually instantiate a storage class using the storages object. ```python >>> from django.core.files.storage import storages >>> storages.backends {'default': {'BACKEND': 'django.core.files.storage.FileSystemStorage'}, 'staticfiles': {'BACKEND': 'django.contrib.staticfiles.storage.StaticFilesStorage'}, 'custom': {'BACKEND': 'package.storage.CustomStorage'}} >>> storage_instance = storages.create_storage({"BACKEND": "package.storage.CustomStorage"}) ``` -------------------------------- ### django.setup(set_prefix=True) Source: https://docs.djangoproject.com/en/5.2/ref/applications Configures Django by loading settings, setting up logging, optionally setting the URL resolver script prefix, and initializing the application registry. ```APIDOC ## django.setup(set_prefix=True) ### Description Configures Django by loading settings, setting up logging, initializing the application registry, and optionally setting the URL resolver script prefix. ### Parameters #### Arguments - **set_prefix** (bool) - Optional - If True, sets the URL resolver script prefix to FORCE_SCRIPT_NAME if defined, or '/' otherwise. Defaults to True. ``` -------------------------------- ### Installing Jinja2 Source: https://docs.djangoproject.com/en/5.2/topics/templates Commands to install the Jinja2 package via pip. ```bash $ python -m pip install Jinja2 ``` ```bash ...\> py -m pip install Jinja2 ``` -------------------------------- ### Create an app using a custom template Source: https://docs.djangoproject.com/en/5.2/ref/django-admin Uses a custom template from a local directory or a remote archive URL to initialize the new app. ```bash django-admin startapp --template=/Users/jezdez/Code/my_app_template myapp ``` ```bash django-admin startapp --template=https://github.com/githubuser/django-app-template/archive/main.zip myapp ``` -------------------------------- ### Build and install GEOS Source: https://docs.djangoproject.com/en/5.2/ref/contrib/gis/install/geolibs Compile and install GEOS using CMake. ```bash $ cmake -DCMAKE_BUILD_TYPE=Release .. $ cmake --build . $ sudo cmake --build . --target install ``` -------------------------------- ### Create model instances Source: https://docs.djangoproject.com/en/5.2/ref/models/querysets Demonstrates the create() method compared to manual instantiation and saving. ```python p = Person.objects.create(first_name="Bruce", last_name="Springsteen") ``` ```python p = Person(first_name="Bruce", last_name="Springsteen") p.save(force_insert=True) ``` -------------------------------- ### Initialize Database Tables Source: https://docs.djangoproject.com/en/5.2/intro/overview Run these commands to generate and apply database migrations based on your defined models. ```bash $ python manage.py makemigrations $ python manage.py migrate ``` ```bash ...\> py manage.py makemigrations ...\> py manage.py migrate ``` -------------------------------- ### Build documentation locally Source: https://docs.djangoproject.com/en/5.2/internals/contributing/writing-documentation Generate HTML documentation from the docs directory. ```bash $ cd docs $ make html ``` ```batch ...\> cd docs ...\> make.bat html ``` -------------------------------- ### Verify Python installation Source: https://docs.djangoproject.com/en/5.2/howto/windows Check the installed Python version in the command prompt. ```text ...\> py --version ``` -------------------------------- ### Install Gunicorn Source: https://docs.djangoproject.com/en/5.2/howto/deployment/wsgi/gunicorn Install the Gunicorn package using the Python package manager. ```bash python -m pip install gunicorn ``` -------------------------------- ### Demonstrate asset path resolution Source: https://docs.djangoproject.com/en/5.2/topics/forms/media Examples showing how Django resolves paths based on STATIC_URL, MEDIA_URL, and staticfiles configuration. ```python >>> from django import forms >>> class CalendarWidget(forms.TextInput): ... class Media: ... css = { ... "all": ["/css/pretty.css"], ... } ... js = ["animations.js", "https://othersite.com/actions.js"] ... >>> w = CalendarWidget() >>> print(w.media) ``` ```python >>> w = CalendarWidget() >>> print(w.media) ``` ```python >>> w = CalendarWidget() >>> print(w.media) ``` -------------------------------- ### Named cycle output example Source: https://docs.djangoproject.com/en/5.2/ref/templates/builtins The resulting output from the named cycle example. ```html ... ... ... ... ``` -------------------------------- ### Run testserver with a fixture Source: https://docs.djangoproject.com/en/5.2/ref/django-admin Starts the development server using data from the specified fixture file. ```bash django-admin testserver mydata.json ``` -------------------------------- ### Install Selenium package Source: https://docs.djangoproject.com/en/5.2/topics/testing/tools Install the required selenium package version 4.8.0 or higher. ```bash $ python -m pip install "selenium >= 4.8.0" ``` ```bash ...\> py -m pip install "selenium >= 4.8.0" ``` -------------------------------- ### View project file structure Source: https://docs.djangoproject.com/en/5.2/intro/tutorial01 The directory layout generated by the startproject command. ```text djangotutorial/ manage.py mysite/ __init__.py settings.py urls.py asgi.py wsgi.py ``` -------------------------------- ### Using the default storage system Source: https://docs.djangoproject.com/en/5.2/topics/files Demonstrates basic file operations like saving, reading, and deleting using the global default storage. ```python >>> from django.core.files.base import ContentFile >>> from django.core.files.storage import default_storage >>> path = default_storage.save("path/to/file", ContentFile(b"new content")) >>> path 'path/to/file' >>> default_storage.size(path) 11 >>> default_storage.open(path).read() b'new content' >>> default_storage.delete(path) >>> default_storage.exists(path) False ``` -------------------------------- ### Install and run isort Source: https://docs.djangoproject.com/en/5.2/internals/contributing/writing-code/coding-style Commands to install and execute isort for automated import sorting. ```bash $ python -m pip install "isort >= 7.0.0" $ isort . ``` ```bash ...\> py -m pip install "isort >= 7.0.0" ...\> isort . ``` -------------------------------- ### Initialize a new Django project Source: https://docs.djangoproject.com/en/5.2/ref/django-admin Creates a new project directory structure at the specified path. ```bash django-admin startproject myproject /Users/jezdez/Code/myproject_repo ``` -------------------------------- ### Verify ReportLab Installation Source: https://docs.djangoproject.com/en/5.2/howto/outputting-pdf Check if the library is correctly installed by importing it in the Python interpreter. ```python >>> import reportlab ``` -------------------------------- ### Initialize and Inspect DataSource Source: https://docs.djangoproject.com/en/5.2/ref/contrib/gis/gdal Create a DataSource instance from a file path and inspect its name and layer count. ```python >>> from django.contrib.gis.gdal import DataSource >>> ds = DataSource("/path/to/your/cities.shp") >>> ds.name '/path/to/your/cities.shp' >>> ds.layer_count # This file only contains one layer 1 ``` -------------------------------- ### Install psycopg via pip Source: https://docs.djangoproject.com/en/5.2/ref/contrib/gis/install Install the PostgreSQL adapter for Python within a virtual environment. ```bash ...\> py -m pip install psycopg ``` -------------------------------- ### Create README.rst for the package Source: https://docs.djangoproject.com/en/5.2/intro/reusable-apps Provides installation and usage instructions for users of the package. ```rst ============ django-polls ============ django-polls is a Django app to conduct web-based polls. For each question, visitors can choose between a fixed number of answers. Detailed documentation is in the "docs" directory. Quick start ----------- 1. Add "polls" to your INSTALLED_APPS setting like this:: INSTALLED_APPS = [ ..., "django_polls", ] 2. Include the polls URLconf in your project urls.py like this:: path("polls/", include("django_polls.urls")), 3. Run ``python manage.py migrate`` to create the models. 4. Start the development server and visit the admin to create a poll. 5. Visit the ``/polls/`` URL to participate in the poll. ``` -------------------------------- ### Install SpatiaLite via Homebrew Source: https://docs.djangoproject.com/en/5.2/ref/contrib/gis/install/spatialite Use Homebrew to install SpatiaLite tools and GDAL on macOS. ```bash $ brew update $ brew install spatialite-tools $ brew install gdal ``` -------------------------------- ### Create Article Instance Source: https://docs.djangoproject.com/en/5.2/topics/db/examples/many_to_many Initialize an Article object. ```python >>> a1 = Article(headline="Django lets you build web apps easily") ``` -------------------------------- ### Install Django test dependencies Source: https://docs.djangoproject.com/en/5.2/intro/contributing Install the necessary Python packages for running the test suite. ```bash $ python -m pip install -r requirements/py3.txt ``` ```bash ...\> py -m pip install -r requirements\py3.txt ``` -------------------------------- ### Install Django Debug Toolbar Source: https://docs.djangoproject.com/en/5.2/intro/tutorial08 Install the package using pip in an activated virtual environment. ```bash $ python -m pip install django-debug-toolbar ``` ```bash ...\> py -m pip install django-debug-toolbar ``` -------------------------------- ### View test database creation output Source: https://docs.djangoproject.com/en/5.2/topics/testing/overview Example output displayed when the test runner initializes the test database. ```text Creating test database... Creating table myapp_animal Creating table myapp_mineral ``` -------------------------------- ### Install locales on Debian-based systems Source: https://docs.djangoproject.com/en/5.2/internals/contributing/writing-code/unit-tests Resolves UnicodeEncodeError failures by installing and configuring system locales. ```bash $ apt-get install locales $ dpkg-reconfigure locales ``` -------------------------------- ### Install test dependencies Source: https://docs.djangoproject.com/en/5.2/internals/contributing/writing-code/unit-tests Install required packages for the full test suite using pip. ```bash $ python -m pip install -r tests/requirements/py3.txt ``` ```batch ...\> py -m pip install -r tests\requirements\py3.txt ``` -------------------------------- ### Example import structure Source: https://docs.djangoproject.com/en/5.2/internals/contributing/writing-code/coding-style Demonstrates the required grouping and sorting order for imports in Django files. ```python # future from __future__ import unicode_literals # standard library import json from itertools import chain # third-party import bcrypt # Django from django.http import Http404 from django.http.response import ( Http404, HttpResponse, HttpResponseNotAllowed, StreamingHttpResponse, cookie, ) # local Django from .models import LogEntry # try/except try: import yaml except ImportError: yaml = None CONSTANT = "foo" class Example: ... ``` -------------------------------- ### Run tests starting at a module Source: https://docs.djangoproject.com/en/5.2/internals/contributing/writing-code/unit-tests Use the --start-at option to begin test execution from a specific top-level module. ```bash $ ./runtests.py --start-at=wsgi ``` ```batch ...\> runtests.py --start-at=wsgi ``` -------------------------------- ### Verify Python Installation Source: https://docs.djangoproject.com/en/5.2/intro/install Run this command in your shell to confirm that Python is correctly installed and accessible. ```bash Python 3.x.y [GCC 4.x] on linux Type "help", "copyright", "credits" or "license" for more information. >>> ``` -------------------------------- ### Initialize migrations for an existing app Source: https://docs.djangoproject.com/en/5.2/topics/migrations Use this command to create an initial migration for an app that already has database tables. ```bash $ python manage.py makemigrations your_app_label ``` -------------------------------- ### Install uWSGI Source: https://docs.djangoproject.com/en/5.2/howto/deployment/wsgi/uwsgi Commands to install the current stable or LTS version of uWSGI using pip. ```bash # Install current stable version. $ python -m pip install uwsgi # Or install LTS (long term support). $ python -m pip install https://projects.unbit.it/downloads/uwsgi-lts.tar.gz ``` -------------------------------- ### Test class-based view context Source: https://docs.djangoproject.com/en/5.2/topics/testing/advanced Instantiate a view and call setup() with a request to test methods outside the full request/response cycle. ```python from django.test import RequestFactory, TestCase from .views import HomeView class HomePageTest(TestCase): def test_environment_set_in_context(self): request = RequestFactory().get("/") view = HomeView() view.setup(request) context = view.get_context_data() self.assertIn("environment", context) ``` -------------------------------- ### Configure spatial database settings for testing Source: https://docs.djangoproject.com/en/5.2/ref/contrib/gis/testing Example settings file using PostGIS backends for all databases to enable GeoDjango test execution. ```python DATABASES = { "default": { "ENGINE": "django.contrib.gis.db.backends.postgis", "NAME": "geodjango", "USER": "geodjango", }, "other": { "ENGINE": "django.contrib.gis.db.backends.postgis", "NAME": "other", "USER": "geodjango", }, } SECRET_KEY = "django_tests_secret_key" ``` -------------------------------- ### Malicious user input examples Source: https://docs.djangoproject.com/en/5.2/ref/templates/language Examples of user input that could trigger XSS if not escaped. ```text ``` ```text username ``` -------------------------------- ### Define Model for exclusion examples Source: https://docs.djangoproject.com/en/5.2/ref/contrib/admin/index Example model structure used to demonstrate field exclusion. ```python from django.db import models class Author(models.Model): name = models.CharField(max_length=100) title = models.CharField(max_length=3) birth_date = models.DateField(blank=True, null=True) ``` -------------------------------- ### Create a virtual environment Source: https://docs.djangoproject.com/en/5.2/intro/contributing Initialize a new virtual environment to manage project dependencies in isolation. ```bash $ python3 -m venv ~/.virtualenvs/djangodev ``` ```batch ...\> py -m venv %HOMEPATH%\.virtualenvs\djangodev ``` -------------------------------- ### Define item GUID permalink status Source: https://docs.djangoproject.com/en/5.2/ref/contrib/syndication Method or attribute to set the isPermaLink attribute for the GUID. ```python def item_guid_is_permalink(self, obj): """ Takes an item, as returned by items(), and returns a boolean. """ item_guid_is_permalink = False # Hard coded value ``` -------------------------------- ### Initialize standalone Django usage Source: https://docs.djangoproject.com/en/5.2/topics/settings Call django.setup() after configuring settings to load the application registry for standalone scripts. ```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 ``` ```python if __name__ == "__main__": import django django.setup() ``` -------------------------------- ### Display directory structure Source: https://docs.djangoproject.com/en/5.2/intro/tutorial01 The resulting file layout after running the startapp command. ```text polls/ __init__.py admin.py apps.py migrations/ __init__.py models.py tests.py views.py ``` -------------------------------- ### Install tblib dependency Source: https://docs.djangoproject.com/en/5.2/ref/django-admin Install the required third-party package for displaying tracebacks during parallel test execution. ```bash $ python -m pip install tblib ``` -------------------------------- ### Instantiate Point Objects Source: https://docs.djangoproject.com/en/5.2/ref/contrib/gis/geos Demonstrates different ways to initialize Point objects using coordinates or sequences. ```python >>> pnt = Point(5, 23) >>> pnt = Point([5, 23]) ``` ```python >>> pnt = Point() >>> pnt = Point([]) ``` -------------------------------- ### Using the Django Test Client Source: https://docs.djangoproject.com/en/5.2/topics/testing/tools Demonstrates the difference between manually instantiating a Client and using the built-in self.client provided by TestCase. ```python import unittest from django.test import Client class SimpleTest(unittest.TestCase): def test_details(self): client = Client() response = client.get("/customer/details/") self.assertEqual(response.status_code, 200) def test_index(self): client = Client() response = client.get("/customer/index/") self.assertEqual(response.status_code, 200) ``` ```python from django.test import TestCase class SimpleTest(TestCase): def test_details(self): response = self.client.get("/customer/details/") self.assertEqual(response.status_code, 200) def test_index(self): response = self.client.get("/customer/index/") self.assertEqual(response.status_code, 200) ``` -------------------------------- ### Setup test environment in shell Source: https://docs.djangoproject.com/en/5.2/intro/tutorial05 Initializes the test environment to enable response context inspection. ```python >>> from django.test.utils import setup_test_environment >>> setup_test_environment() ``` -------------------------------- ### Configure uWSGI with INI file Source: https://docs.djangoproject.com/en/5.2/howto/deployment/wsgi/uwsgi Example of a configuration file for uWSGI to manage project settings. ```ini [uwsgi] chdir=/path/to/your/project module=mysite.wsgi:application master=True pidfile=/tmp/project-master.pid vacuum=True max-requests=5000 daemonize=/var/log/uwsgi/yourproject.log ``` -------------------------------- ### Install JavaScript test dependencies Source: https://docs.djangoproject.com/en/5.2/internals/contributing/writing-code/javascript Commands to install required Node.js dependencies for running JavaScript tests. ```bash $ npm install ``` ```cmd ...\> npm install ``` -------------------------------- ### Run Django with Uvicorn Source: https://docs.djangoproject.com/en/5.2/howto/deployment/asgi/uvicorn Start the development server by pointing to the ASGI application object in your project. ```bash python -m uvicorn myproject.asgi:application ``` -------------------------------- ### Initialize a formset with data Source: https://docs.djangoproject.com/en/5.2/topics/forms/formsets Demonstrates creating a formset with initial data and two extra forms, then iterating through the resulting forms. ```python >>> import datetime >>> from django.forms import formset_factory >>> from myapp.forms import ArticleForm >>> ArticleFormSet = formset_factory(ArticleForm, extra=2) >>> formset = ArticleFormSet( ... initial=[ ... { ... "title": "Django is now open source", ... "pub_date": datetime.date.today(), ... } ... ] ... ) >>> for form in formset: ... print(form) ...
``` -------------------------------- ### Unsorted cities list example Source: https://docs.djangoproject.com/en/5.2/ref/templates/builtins An example of an unsorted list that demonstrates why pre-sorting is necessary for correct grouping. ```python cities = [ {"name": "Mumbai", "population": "19,000,000", "country": "India"}, {"name": "New York", "population": "20,000,000", "country": "USA"}, {"name": "Calcutta", "population": "15,000,000", "country": "India"}, {"name": "Chicago", "population": "7,000,000", "country": "USA"}, {"name": "Tokyo", "population": "33,000,000", "country": "Japan"}, ] ``` -------------------------------- ### Runserver Command Examples Source: https://docs.djangoproject.com/en/5.2/ref/django-admin Various ways to invoke the runserver command with different address and port configurations. ```bash django-admin runserver ``` ```bash django-admin runserver 1.2.3.4:8000 ``` ```bash django-admin runserver 7000 ``` ```bash django-admin runserver 1.2.3.4:7000 ``` ```bash django-admin runserver -6 ``` ```bash django-admin runserver -6 7000 ``` ```bash django-admin runserver [2001:0db8:1234:5678::9]:7000 ``` ```bash django-admin runserver localhost:8000 ``` ```bash django-admin runserver -6 localhost:8000 ``` -------------------------------- ### Perform GET Requests Source: https://docs.djangoproject.com/en/5.2/topics/testing/tools Execute GET requests with query parameters, custom headers, and WSGI environment variables. ```python >>> c = Client() >>> c.get("/customers/details/", query_params={"name": "fred", "age": 7}) ``` ```python /customers/details/?name=fred&age=7 ``` ```python >>> c = Client() >>> c.get( ... "/customers/details/", ... query_params={"name": "fred", "age": 7}, ... headers={"accept": "application/json"}, ... ) ``` ```python >>> c = Client() >>> c.get("/", SCRIPT_NAME="/app/") ``` ```python >>> c = Client() >>> c.get("/customers/details/?name=fred&age=7") ``` -------------------------------- ### Install geospatial libraries on Debian/Ubuntu Source: https://docs.djangoproject.com/en/5.2/ref/contrib/gis/install/geolibs Use this command to install the necessary geospatial dependencies on Debian or Ubuntu systems. ```bash $ sudo apt-get install binutils libproj-dev gdal-bin ``` -------------------------------- ### Define test data with setUpTestData Source: https://docs.djangoproject.com/en/5.2/topics/testing/tools Use setUpTestData to create initial data once for the entire TestCase class, improving test performance. ```python from django.test import TestCase 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 ... def test2(self): # Some other test using self.foo ... ``` -------------------------------- ### Initialize a GeoDjango project Source: https://docs.djangoproject.com/en/5.2/ref/contrib/gis/tutorial Use the django-admin script to create the base project directory. ```bash $ django-admin startproject geodjango ``` ```bash ...\> django-admin startproject geodjango ``` -------------------------------- ### Install GeoDjango Prerequisites via MacPorts Source: https://docs.djangoproject.com/en/5.2/ref/contrib/gis/install Use MacPorts to install PostgreSQL, GEOS, PROJ, PostGIS, GDAL, and libgeoip. ```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 ``` -------------------------------- ### Build HTML documentation with Makefile Source: https://docs.djangoproject.com/en/5.2/intro/whatsnext Generate HTML documentation from the source files using GNU Make. ```bash $ cd path/to/django/docs $ make html ``` -------------------------------- ### Implementing a Custom Management Command Source: https://docs.djangoproject.com/en/5.2/howto/custom-management-commands Example of a command class that accepts arguments and performs database operations. ```python from django.core.management.base import BaseCommand, CommandError from polls.models import Question as Poll class Command(BaseCommand): help = "Closes the specified poll for voting" def add_arguments(self, parser): parser.add_argument("poll_ids", nargs="+", type=int) def handle(self, *args, **options): for poll_id in options["poll_ids"]: try: poll = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise CommandError('Poll "%s" does not exist' % poll_id) poll.opened = False poll.save() self.stdout.write( self.style.SUCCESS('Successfully closed poll "%s"' % poll_id) ) ```