### Setup test environment Source: https://docs.djangoproject.com/en/4.2/_modules/django/test/runner Initializes the test environment and installs the unittest signal handler. ```python def setup_test_environment(self, **kwargs): setup_test_environment(debug=self.debug_mode) unittest.installHandler() ``` -------------------------------- ### Run development server with various address and port configurations Source: https://docs.djangoproject.com/en/4.2/ref/django-admin Examples of starting the development server using different IP addresses, ports, and IPv6 settings. ```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 ``` -------------------------------- ### Start uWSGI server via command line Source: https://docs.djangoproject.com/en/4.2/howto/deployment/wsgi/uwsgi Example command to launch the uWSGI server with common configuration flags 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 ``` -------------------------------- ### Perform pre-test setup Source: https://docs.djangoproject.com/en/4.2/_modules/django/test/testcases Handles application registry restriction and fixture installation before test execution. ```python @classmethod def _pre_setup(cls): """ Perform pre-test setup: * If the class has an 'available_apps' attribute, restrict the app registry to these applications, then fire the post_migrate signal -- it must run with the correct set of applications for the test case. * If the class has a 'fixtures' attribute, install those fixtures. """ super()._pre_setup() if cls.available_apps is not None: apps.set_available_apps(cls.available_apps) cls._available_apps_calls_balanced += 1 setting_changed.send( sender=settings._wrapped.__class__, setting="INSTALLED_APPS", value=cls.available_apps, enter=True, ) for db_name in cls._databases_names(include_mirrors=False): emit_post_migrate_signal(verbosity=0, interactive=False, db=db_name) try: cls._fixture_setup() except Exception: if cls.available_apps is not None: apps.unset_available_apps() setting_changed.send( sender=settings._wrapped.__class__, setting="INSTALLED_APPS", value=settings.INSTALLED_APPS, enter=False, ) raise # Clear the queries_log so that it's less likely to overflow (a single # test probably won't execute 9K queries). If queries_log overflows, # then assertNumQueries() doesn't work. for db_name in cls._databases_names(include_mirrors=False): connections[db_name].queries_log.clear() ``` -------------------------------- ### Build and install PROJ Source: https://docs.djangoproject.com/en/4.2/ref/contrib/gis/install/geolibs Configure and install PROJ using CMake. ```bash $ cmake .. $ cmake --build . $ sudo cmake --build . --target install ``` -------------------------------- ### Install Uvicorn and Gunicorn Source: https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/uvicorn Install both Uvicorn and Gunicorn for production deployment. ```bash python -m pip install uvicorn gunicorn ``` -------------------------------- ### Define a model with HStoreField Source: https://docs.djangoproject.com/en/4.2/ref/contrib/postgres/fields Example model setup for demonstrating HStoreField queries. ```python from django.contrib.postgres.fields import HStoreField from django.db import models class Dog(models.Model): name = models.CharField(max_length=200) data = HStoreField() def __str__(self): return self.name ``` -------------------------------- ### Install and run tox Source: https://docs.djangoproject.com/en/4.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 pre-commit hooks Source: https://docs.djangoproject.com/en/4.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 ``` ```batch ...\> py -m pip install pre-commit ...\> pre-commit install ``` -------------------------------- ### Install Selenium package Source: https://docs.djangoproject.com/en/4.2/topics/testing/tools Command to install the required selenium package for browser automation. ```bash $ python -m pip install "selenium >= 3.8.0" ``` ```bash ...\> py -m pip install "selenium >= 3.8.0" ``` -------------------------------- ### Django Module Initialization and Setup Source: https://docs.djangoproject.com/en/4.2/_modules/django Defines the Django version and provides a setup function to initialize settings, logging, and the application registry. ```python from django.utils.version import get_version VERSION = (6, 0, 3, "final", 0) __version__ = get_version(VERSION) [docs] def setup(set_prefix=True): """ Configure the settings (this happens as a side effect of accessing the first setting), configure logging and populate the app registry. Set the thread-local urlresolvers script prefix if `set_prefix` is True. """ from django.apps import apps from django.conf import settings from django.urls import set_script_prefix from django.utils.log import configure_logging configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) if set_prefix: set_script_prefix( "/" if settings.FORCE_SCRIPT_NAME is None else settings.FORCE_SCRIPT_NAME ) apps.populate(settings.INSTALLED_APPS) ``` -------------------------------- ### Install Sphinx documentation tool Source: https://docs.djangoproject.com/en/4.2/internals/contributing/writing-documentation Installs the Sphinx package required to build Django documentation locally. ```bash $ python -m pip install Sphinx ``` ```batch ...\> py -m pip install Sphinx ``` -------------------------------- ### Install Django in editable mode Source: https://docs.djangoproject.com/en/4.2/intro/contributing Install the local clone of Django in editable mode so 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\ ``` -------------------------------- ### Retrieve objects with get() Source: https://docs.djangoproject.com/en/4.2/ref/models/querysets Examples of using get() to retrieve a single object, including handling 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.") ``` -------------------------------- ### Superuser creation prompts Source: https://docs.djangoproject.com/en/4.2/intro/tutorial02 Example interaction flow for setting up the superuser credentials. ```text Username: admin ``` ```text Email address: admin@example.com ``` ```text Password: ********** Password (again): ********* Superuser created successfully. ``` -------------------------------- ### Perform pre-test setup Source: https://docs.djangoproject.com/en/4.2/_modules/django/test/testcases Initializes the test client and clears the mail outbox. ```python @classmethod def _pre_setup(cls): """ Perform pre-test setup: * Create a test client. * Clear the mail test outbox. """ cls.client = cls.client_class() cls.async_client = cls.async_client_class() mail.outbox = [] ``` -------------------------------- ### Install and run a local SMTP server with aiosmtpd Source: https://docs.djangoproject.com/en/4.2/topics/email Use these commands to install the aiosmtpd package and start a local SMTP server on port 8025 for inspecting email output. ```bash python -m pip install aiosmtpd python -m aiosmtpd -n -l localhost:8025 ``` -------------------------------- ### Implementing storage with settings Source: https://docs.djangoproject.com/en/4.2/howto/custom-file-storage Example of initializing a storage class by pulling configuration from Django settings. ```python from django.conf import settings from django.core.files.storage import Storage class MyStorage(Storage): def __init__(self, option=None): if not option: option = settings.CUSTOM_STORAGE_OPTIONS ... ``` -------------------------------- ### RequestFactory usage example Source: https://docs.djangoproject.com/en/4.2/_modules/django/test/client Basic instantiation and usage of RequestFactory to create GET and POST requests. ```python rf = RequestFactory() get_request = rf.get('/hello/') post_request = rf.post('/submit/', {'foo': 'bar'}) ``` -------------------------------- ### Define a model with ArrayField Source: https://docs.djangoproject.com/en/4.2/ref/contrib/postgres/fields Example model setup used for demonstrating custom lookups on an ArrayField. ```python from django.contrib.postgres.fields import ArrayField from django.db import models class Post(models.Model): name = models.CharField(max_length=200) tags = ArrayField(models.CharField(max_length=200), blank=True) def __str__(self): return self.name ``` -------------------------------- ### Example TEMPLATES search configuration Source: https://docs.djangoproject.com/en/4.2/topics/templates Demonstrates a multi-engine configuration to illustrate the template search order. ```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", ], }, ] ``` -------------------------------- ### Setup Test Databases Source: https://docs.djangoproject.com/en/4.2/_modules/django/test/runner Initializes the test databases using the runner's configuration settings. ```python def setup_databases(self, **kwargs): return _setup_databases( self.verbosity, self.interactive, time_keeper=self.time_keeper, keepdb=self.keepdb, debug_sql=self.debug_sql, parallel=self.parallel, **kwargs, ) ``` -------------------------------- ### pre_migrate Source: https://docs.djangoproject.com/en/4.2/ref/signals The pre_migrate signal is sent by the migrate command before it starts to install an application. It provides context about the migration process, including verbosity, interactivity, and the migration plan. ```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 manage.py is printing. - **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 will operate. - **plan** (list) - The migration plan that is going to be used. - **apps** (Apps) - An instance of Apps containing the state of the project before the migration run. ``` -------------------------------- ### Instantiating a Model Source: https://docs.djangoproject.com/en/4.2/ref/signals Example of creating a model instance, which triggers pre_init and post_init signals. ```python q = Question(question_text="What's new?", pub_date=timezone.now()) ``` -------------------------------- ### Start Development Server Source: https://docs.djangoproject.com/en/4.2/intro/tutorial06 Commands to launch the Django development server. ```bash $ python manage.py runserver ``` ```bash ...\> py manage.py runserver ``` -------------------------------- ### Install Jinja2 Source: https://docs.djangoproject.com/en/4.2/topics/templates Install the Jinja2 package using pip. ```bash $ python -m pip install Jinja2 ``` ```bash ...\> py -m pip install Jinja2 ``` -------------------------------- ### Run testserver with addrport and multiple fixtures Source: https://docs.djangoproject.com/en/4.2/ref/django-admin Demonstrates specifying a custom port and multiple fixtures, showing that the order of arguments does not affect the command execution. ```bash django-admin testserver --addrport 7000 fixture1 fixture2 django-admin testserver fixture1 fixture2 --addrport 7000 ``` -------------------------------- ### Install Gunicorn Source: https://docs.djangoproject.com/en/4.2/howto/deployment/wsgi/gunicorn Use pip to install the Gunicorn package. ```bash python -m pip install gunicorn ``` -------------------------------- ### Install Uvicorn Source: https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/uvicorn Install the Uvicorn package using pip. ```bash python -m pip install uvicorn ``` -------------------------------- ### Install Core Django Tables Source: https://docs.djangoproject.com/en/4.2/howto/legacy-databases Run migrations to set up necessary Django-specific tables like admin permissions and content types. ```bash $ python manage.py migrate ``` -------------------------------- ### Install Daphne Source: https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/daphne Use pip to install the Daphne package. ```bash python -m pip install daphne ``` -------------------------------- ### django.setup(set_prefix=True) Source: https://docs.djangoproject.com/en/4.2/ref/applications Configures Django by loading settings, setting up logging, optionally setting the URL resolver script prefix, and initializing the application registry. This must be called explicitly in standalone Python scripts. ```APIDOC ## django.setup(set_prefix=True) ### Description Configures Django by loading settings, setting up logging, and initializing the application registry. This function is called automatically by Django's ASGI/WSGI servers and management commands, but must be called explicitly in standalone Python scripts. ### 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. ``` -------------------------------- ### Initialize Database Tables Source: https://docs.djangoproject.com/en/4.2/intro/tutorial02 Executes the migration command to create necessary database tables based on the INSTALLED_APPS configuration. ```bash $ python manage.py migrate ``` ```bash ...\> py manage.py migrate ``` -------------------------------- ### Build and install GEOS Source: https://docs.djangoproject.com/en/4.2/ref/contrib/gis/install/geolibs Compile and install the GEOS library using CMake. ```bash $ cmake -DCMAKE_BUILD_TYPE=Release .. $ cmake --build . $ sudo cmake --build . --target install ``` -------------------------------- ### Verify ReportLab installation Source: https://docs.djangoproject.com/en/4.2/howto/outputting-pdf Test the installation by importing the library in the Python interpreter. ```python >>> import reportlab ``` -------------------------------- ### Install Hypercorn Source: https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/hypercorn Use pip to install the Hypercorn package into your Python environment. ```bash python -m pip install hypercorn ``` -------------------------------- ### Configure PostgreSQL Database Source: https://docs.djangoproject.com/en/4.2/ref/settings Configuration example for a PostgreSQL database including user credentials and connection details. ```python DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": "mydatabase", "USER": "mydatabaseuser", "PASSWORD": "mypassword", "HOST": "127.0.0.1", "PORT": "5432", } } ``` -------------------------------- ### Initialize InMemoryStorage Source: https://docs.djangoproject.com/en/4.2/_modules/django/core/files/storage/memory Sets up the in-memory storage root and connects to setting change signals. ```python @deconstructible(path="django.core.files.storage.InMemoryStorage") class InMemoryStorage(Storage, StorageSettingsMixin): """A storage saving files in memory.""" def __init__( self, location=None, base_url=None, file_permissions_mode=None, directory_permissions_mode=None, ): self._location = location self._base_url = base_url self._file_permissions_mode = file_permissions_mode self._directory_permissions_mode = directory_permissions_mode self._root = InMemoryDirNode() self._resolve( self.base_location, create_if_missing=True, leaf_cls=InMemoryDirNode ) setting_changed.connect(self._clear_cached_properties) ``` -------------------------------- ### ArrayAgg ordering examples Source: https://docs.djangoproject.com/en/4.2/ref/contrib/postgres/aggregates Examples of valid ordering arguments for the ArrayAgg aggregate. ```python "some_field" "-some_field" from django.db.models import F F("some_field").desc() ``` -------------------------------- ### Setup Test Databases Source: https://docs.djangoproject.com/en/4.2/_modules/django/test/utils Creates and configures test databases, including handling mirrors and serialization for test isolation. ```python def setup_databases( verbosity, interactive, *, time_keeper=None, keepdb=False, debug_sql=False, parallel=0, aliases=None, serialized_aliases=None, **kwargs, ): """Create the test databases.""" if time_keeper is None: time_keeper = NullTimeKeeper() test_databases, mirrored_aliases = get_unique_databases_and_mirrors(aliases) old_names = [] serialize_connections = [] for db_name, aliases in test_databases.values(): first_alias = None for alias in aliases: connection = connections[alias] old_names.append((connection, db_name, first_alias is None)) # Actually create the database for the first connection if first_alias is None: first_alias = alias with time_keeper.timed(" Creating '%s'" % alias): connection.creation.create_test_db( verbosity=verbosity, autoclobber=not interactive, keepdb=keepdb, ) if serialized_aliases is None or alias in serialized_aliases: serialize_connections.append(connection) if parallel > 1: for index in range(parallel): with time_keeper.timed(" Cloning '%s'" % alias): connection.creation.clone_test_db( suffix=str(index + 1), verbosity=verbosity, keepdb=keepdb, ) # Configure all other connections as mirrors of the first one else: connections[alias].creation.set_as_test_mirror( connections[first_alias].settings_dict ) # Configure the test mirrors. for alias, mirror_alias in mirrored_aliases.items(): connections[alias].creation.set_as_test_mirror( connections[mirror_alias].settings_dict ) # Serialize content of test databases only once all of them are setup to # account for database mirroring and routing during serialization. This # slightly horrific process is so people who are testing on databases # without transactions or using TransactionTestCase still get a clean # database on every test run. for serialize_connection in serialize_connections: serialize_connection._test_serialized_contents = ( serialize_connection.creation.serialize_db_to_string() ) if debug_sql: for alias in connections: connections[alias].force_debug_cursor = True return old_names ``` -------------------------------- ### Install and run isort Source: https://docs.djangoproject.com/en/4.2/internals/contributing/writing-code/coding-style Commands to install and execute isort for automatic import sorting. ```bash $ python -m pip install "isort >= 5.1.0" $ isort . ``` ```bash ...\> py -m pip install "isort >= 5.1.0" ...\> isort . ``` -------------------------------- ### Run testserver with a fixture Source: https://docs.djangoproject.com/en/4.2/ref/django-admin Starts the development server using data from the specified JSON fixture file. ```bash django-admin testserver mydata.json ``` -------------------------------- ### Load Fixtures via Command Line Source: https://docs.djangoproject.com/en/4.2/topics/db/fixtures Use the loaddata management command to load initial data into the database. ```bash django-admin loaddata ``` ```bash django-admin loaddata mydata.json ``` ```bash django-admin loaddata mydata ``` ```bash django-admin loaddata foo/bar/mydata.json ``` ```bash django-admin loaddata mammals birds insects ``` -------------------------------- ### Verify Python installation Source: https://docs.djangoproject.com/en/4.2/howto/windows Check the installed Python version via the command prompt. ```text ...\> py --version ``` -------------------------------- ### Named cycle output example Source: https://docs.djangoproject.com/en/4.2/ref/templates/builtins The resulting HTML output from the named cycle example. ```html ... ... ... ... ``` -------------------------------- ### Run Command from Arguments Source: https://docs.djangoproject.com/en/4.2/_modules/django/core/management/base Sets up the environment and executes the command, handling CommandError exceptions and ensuring database connections are closed. ```python def run_from_argv(self, argv): """ Set up any environment changes requested (e.g., Python path and Django settings), then run this command. If the command raises a ``CommandError``, intercept it and print it sensibly to stderr. If the ``--traceback`` option is present or the raised ``Exception`` is not ``CommandError``, raise it. """ self._called_from_command_line = True parser = self.create_parser(argv[0], argv[1]) options = parser.parse_args(argv[2:]) cmd_options = vars(options) # Move positional args out of options to mimic legacy optparse args = cmd_options.pop("args", ()) handle_default_options(options) try: self.execute(*args, **cmd_options) except CommandError as e: if options.traceback: raise # SystemCheckError takes care of its own formatting. if isinstance(e, SystemCheckError): self.stderr.write(str(e), lambda x: x) else: self.stderr.write("%s: %s" % (e.__class__.__name__, e)) sys.exit(e.returncode) finally: try: connections.close_all() except ImproperlyConfigured: # Ignore if connections aren't setup at this point (e.g. no # configured settings). pass ``` -------------------------------- ### Prepare PROJ build directory Source: https://docs.djangoproject.com/en/4.2/ref/contrib/gis/install/geolibs Create and enter a build directory within the PROJ source tree. ```bash $ cd proj-X.Y.Z $ mkdir build $ cd build ``` -------------------------------- ### HTML Tag Injection Example Source: https://docs.djangoproject.com/en/4.2/ref/templates/language Example of a user-provided string containing an HTML tag. ```html username ``` -------------------------------- ### Malicious Script Injection Example Source: https://docs.djangoproject.com/en/4.2/ref/templates/language Example of a user-provided string containing a script tag. ```html ``` -------------------------------- ### Initialize AppConfig with ready() Source: https://docs.djangoproject.com/en/4.2/ref/applications Override the ready method to perform initialization tasks like registering signals. Avoid database interactions within this method to prevent execution during management commands. ```python from django.apps import AppConfig from django.db.models.signals import pre_save class RockNRollConfig(AppConfig): # ... def ready(self): # importing model classes from .models import MyModel # or... MyModel = self.get_model("MyModel") # registering signals with the model's string label pre_save.connect(receiver, sender="app_label.MyModel") ``` -------------------------------- ### Create a virtual environment Source: https://docs.djangoproject.com/en/4.2/intro/contributing Initialize a new virtual environment to isolate project dependencies. ```bash $ python3 -m venv ~/.virtualenvs/djangodev ``` ```batch ...\> py -m venv %HOMEPATH%\.virtualenvs\djangodev ``` -------------------------------- ### Install SpatiaLite via Homebrew Source: https://docs.djangoproject.com/en/4.2/ref/contrib/gis/install/spatialite Use Homebrew to install necessary spatial packages on macOS. ```bash $ brew update $ brew install spatialite-tools $ brew install gdal ``` -------------------------------- ### Install locales on Debian-based systems Source: https://docs.djangoproject.com/en/4.2/internals/contributing/writing-code/unit-tests Resolves UnicodeEncodeError failures by installing and configuring system locales. ```bash $ apt-get install locales $ dpkg-reconfigure locales ``` -------------------------------- ### Setup Test Environment Source: https://docs.djangoproject.com/en/4.2/intro/tutorial05 Initializes the test environment to enable response attribute inspection. ```python >>> from django.test.utils import setup_test_environment >>> setup_test_environment() ``` -------------------------------- ### Define URL patterns and include them Source: https://docs.djangoproject.com/en/4.2/ref/templates/builtins Example configuration for URL patterns and including app-specific URLs. ```python path("client//", app_views.client, name="app-views-client") ``` ```python path("clients/", include("project_name.app_name.urls")) ``` -------------------------------- ### Install Required Python Packages Source: https://docs.djangoproject.com/en/4.2/internals/howto-release-django Install the build and twine packages required for the release process. ```bash $ python -m pip install build twine ``` -------------------------------- ### Initialize migrations for an existing app Source: https://docs.djangoproject.com/en/4.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 ``` -------------------------------- ### Verify Python Installation Source: https://docs.djangoproject.com/en/4.2/intro/install Run this command in your shell to confirm Python is installed and check the version. ```bash Python 3.x.y [GCC 4.x] on linux Type "help", "copyright", "credits" or "license" for more information. >>> ``` -------------------------------- ### Install JavaScript test dependencies Source: https://docs.djangoproject.com/en/4.2/internals/contributing/writing-code/javascript Commands to install necessary Node.js dependencies for running tests. ```bash $ npm install ``` ```cmd ...\> npm install ``` -------------------------------- ### Initialize and Inspect a DataSource Source: https://docs.djangoproject.com/en/4.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 ``` -------------------------------- ### Apply Migrations Source: https://docs.djangoproject.com/en/4.2/ref/contrib/gis/tutorial Execute the migrations to create the database tables. ```bash $ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, world Running migrations: ... Applying world.0001_initial... OK ``` ```bash ...\> py manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, world Running migrations: ... Applying world.0001_initial... OK ``` -------------------------------- ### Install uWSGI Source: https://docs.djangoproject.com/en/4.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 ``` -------------------------------- ### Define item GUID permalink status Source: https://docs.djangoproject.com/en/4.2/ref/contrib/syndication Methods and attributes for setting the isPermaLink attribute of 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 ``` -------------------------------- ### Instantiate Point Objects Source: https://docs.djangoproject.com/en/4.2/ref/contrib/gis/geos Demonstrates different ways to initialize a Point object using coordinates. ```python >>> pnt = Point(5, 23) >>> pnt = Point([5, 23]) ``` ```python >>> pnt = Point() >>> pnt = Point([]) ``` -------------------------------- ### Perform an asynchronous GET request Source: https://docs.djangoproject.com/en/4.2/topics/testing/tools Demonstrates how to initialize the AsyncClient and perform a GET request with headers. ```python >>> c = AsyncClient() >>> c.get("/customers/details/", {"name": "fred", "age": 7}, ACCEPT="application/json") ``` -------------------------------- ### Initialize a Django app Source: https://docs.djangoproject.com/en/4.2/intro/tutorial01 Run this command in the directory containing manage.py to generate the standard application file structure. ```bash $ python manage.py startapp polls ``` ```bash ...\> py manage.py startapp polls ``` -------------------------------- ### Handle Redirects in GET Requests Source: https://docs.djangoproject.com/en/4.2/topics/testing/tools Follow redirects during a GET request and inspect the redirect chain. ```python >>> response = c.get("/redirect_me/", follow=True) >>> response.redirect_chain [('http://testserver/next/', 302), ('http://testserver/final/', 302)] ``` -------------------------------- ### Create Cache Table Source: https://docs.djangoproject.com/en/4.2/topics/cache Run this management command to initialize the database table required for the cache backend. ```bash python manage.py createcachetable ``` -------------------------------- ### Create an object using create() Source: https://docs.djangoproject.com/en/4.2/ref/models/querysets Demonstrates the shorthand for creating and saving a model instance. ```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) ``` -------------------------------- ### Install GeoDjango prerequisites via MacPorts Source: https://docs.djangoproject.com/en/4.2/ref/contrib/gis/install Use MacPorts to install the necessary database and GIS libraries. ```bash $ sudo port install postgresql13-server $ sudo port install geos $ sudo port install proj6 $ sudo port install postgis3 $ sudo port install gdal $ sudo port install libgeoip ``` -------------------------------- ### Run testserver with specific IP and port Source: https://docs.djangoproject.com/en/4.2/ref/django-admin Starts the test server on a specific IP address and port using a single fixture. ```bash django-admin testserver --addrport 1.2.3.4:7000 test ``` -------------------------------- ### Install GeoDjango prerequisites via Homebrew Source: https://docs.djangoproject.com/en/4.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 ``` -------------------------------- ### Initialize a new Django project Source: https://docs.djangoproject.com/en/4.2/intro/tutorial01 Use the django-admin command to generate the project directory structure. Ensure the project name does not conflict with existing Python or Django packages. ```bash $ django-admin startproject mysite ``` ```bash ...\> django-admin startproject mysite ``` -------------------------------- ### Install a local Django package Source: https://docs.djangoproject.com/en/4.2/intro/reusable-apps Use pip to install a packaged Django application from a distribution file. ```bash python -m pip install --user django-polls/dist/django_polls-0.1.tar.gz ``` -------------------------------- ### Initialize standalone Django usage Source: https://docs.djangoproject.com/en/4.2/topics/settings Call django.setup() after configuring settings to populate 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() ```