### Install nanodjango - Bash Source: https://github.com/radiac/nanodjango/blob/main/docs/get_started.rst Installs the nanodjango package using the pip package manager. This is the first step required to start using nanodjango. ```bash pip install nanodjango ``` -------------------------------- ### Run nanodjango App - Bash Source: https://github.com/radiac/nanodjango/blob/main/docs/get_started.rst Executes the specified nanodjango application script. This command automatically handles initial setup steps like creating and applying database migrations. ```bash nanodjango run counter.py ``` -------------------------------- ### Serve nanodjango App with Gunicorn - Bash Source: https://github.com/radiac/nanodjango/blob/main/docs/get_started.rst Demonstrates how to serve the nanodjango application using gunicorn for production or production-like environments. ```bash nanodjango serve counter.py ``` -------------------------------- ### Execute nanodjango Management Commands - Bash Source: https://github.com/radiac/nanodjango/blob/main/docs/get_started.rst Shows how to use the `nanodjango manage` command to run standard Django management commands. Examples include creating migrations, applying migrations, and creating a superuser. ```bash nanodjango manage counter.py makemigrations counter nanodjango manage counter.py migrate nanodjango manage counter.py createsuperuser nanodjango manage counter.py ``` -------------------------------- ### Running a Project Example - Bash Source: https://github.com/radiac/nanodjango/blob/main/docs/contributing.rst Navigates to the examples directory, sets the PYTHONPATH to include the project root, and runs a specific example script ('counter.py') using the nanodjango module's run command with the 'migrate' argument. This demonstrates how to execute project examples within the development setup. ```bash (.venv) nanodjango$ cd examples (.venv) examples$ PYTHONPATH=.. (.venv) examples$ python -m nanodjango run counter.py migrate ``` -------------------------------- ### Convert nanodjango App to Full Django Project - Bash Source: https://github.com/radiac/nanodjango/blob/main/docs/get_started.rst Provides the command to automatically convert the simple nanodjango script file into a complete, standard Django project structure at the specified path. ```bash nanodjango counter.py convert /path/to/site --name=myproject ``` -------------------------------- ### Running nanodjango Script and Migrations (Bash) Source: https://github.com/radiac/nanodjango/blob/main/docs/tutorial.rst Provides the command-line instruction to execute the nanodjango script (`counter.py`). Running the script this way automatically handles database setup, including creating and applying migrations for defined models. ```bash nanodjango run counter.py ``` -------------------------------- ### Serving with Gunicorn/Uvicorn Directly (Bash) Source: https://github.com/radiac/nanodjango/blob/main/docs/tutorial.rst Shows alternative command-line examples for serving the nanodjango application using standard Python WSGI servers like Gunicorn or ASGI servers like Uvicorn, specifying the nanodjango script file and the callable application instance (`counter:app`). ```bash gunicorn -w 4 counter:app uwsgi --wsgi-file counter.py --callable app --processes 4 uvicorn counter:app ``` -------------------------------- ### Complex Model, Form, and View Example (Python) Source: https://github.com/radiac/nanodjango/blob/main/docs/tutorial.rst A comprehensive example showing how to define a model (`Author`), create a Django `ModelForm` for it, and build a view (`add_author`) that processes form data, performs validation, saves to the database, and renders a template, similar to standard Django practices. ```python @app.admin class Author(models.Model): name = models.CharField(max_length=100) birth_date = models.DateField(blank=True, null=True) class AuthorForm(ModelForm): class Meta: model = Author fields = ["name", "birth_date"] @app.route("add/") def add_author(request): form = AuthorForm(request.POST or None) if form.is_valid(): form.save() return "Author added" return render(request, "form.html", {'form': form}) ``` -------------------------------- ### Building Documentation Locally - Bash Source: https://github.com/radiac/nanodjango/blob/main/docs/contributing.rst Installs dependencies required for building documentation from 'docs/requirements.txt', navigates to the 'docs' directory, and runs the 'make html' command to generate the HTML documentation files. The output is placed in 'docs/_build/html/'. ```bash (.venv) nanodjango$ pip install -r docs/requirements.txt (.venv) nanodjango$ cd docs (.venv) docs$ make html ``` -------------------------------- ### Running Converted Django Project (Bash) Source: https://github.com/radiac/nanodjango/blob/main/docs/tutorial.rst Shows the standard Bash commands required to navigate into the directory of the newly converted Django project and run the development server using the standard `manage.py` script. ```bash cd /path/to/site ./manage.py runserver 0:8000 ``` -------------------------------- ### Initializing nanodjango with Defaults (Python) Source: https://github.com/radiac/nanodjango/blob/main/docs/tutorial.rst Imports the `Django` class from the nanodjango library and creates a basic instance named `app`. This instance serves as the central object for configuring the application with sensible defaults. ```python from nanodjango import Django app = Django() ``` -------------------------------- ### Define nanodjango App with Views and API - Python Source: https://github.com/radiac/nanodjango/blob/main/docs/get_started.rst Creates a minimal nanodjango application script. It defines a Django model, registers it with the admin, adds a standard Django function view for the root URL, and includes a Django Ninja API endpoint. ```python from django.db import models from nanodjango import Django app = Django() @app.admin class CountLog(models.Model): timestamp = models.DateTimeField(auto_now_add=True) @app.route("/") def count(request): # Standard Django function view CountLog.objects.create() return f"

Number of requests: {CountLog.objects.count()}

" @app.api.get("/add") def count(request): # Django Ninja API CountLog.objects.create() return {"count": CountLog.objects.count()} ``` -------------------------------- ### Initializing nanodjango with Custom Settings (Python) Source: https://github.com/radiac/nanodjango/blob/main/docs/tutorial.rst Demonstrates how to pass standard Django settings and nanodjango-specific settings (like `ADMIN_URL`) as keyword arguments to the `Django` constructor during initialization. This allows customization beyond the default configuration. ```python app = Django( ADMIN_URL="secret_admin/", SECRET_KEY=os.environ["DJANGO_SECRET_KEY"], ALLOWED_HOSTS=["localhost", "my.example.com"], DEBUG=False, ) ``` -------------------------------- ### Converting to Full Django Project (Bash) Source: https://github.com/radiac/nanodjango/blob/main/docs/tutorial.rst Provides the command-line instruction to use the `nanodjango convert` command. This utility transforms a single-file nanodjango script into a standard Django project structure, suitable for larger applications. ```bash nanodjango convert counter.py /path/to/site --name=myproject ``` -------------------------------- ### Setting Up Development Environment (macOS/Linux) - Bash Source: https://github.com/radiac/nanodjango/blob/main/docs/contributing.rst Creates a Python virtual environment named '.venv', activates it, upgrades pip, and installs project dependencies from 'requirements.txt'. This isolates project dependencies from the system Python environment. ```bash nanodjango$ python -m venv .venv nanodjango$ source .venv/bin/activate (.venv) nanodjango$ pip install --upgrade pip (.venv) nanodjango$ pip install -r requirements.txt ``` -------------------------------- ### Setting Up Development Environment (Windows) - Batch Source: https://github.com/radiac/nanodjango/blob/main/docs/contributing.rst Creates a Python virtual environment named '.venv', activates it using the Windows script, upgrades pip, and installs project dependencies from 'requirements.txt'. This isolates project dependencies for Windows development. ```batch nanodjango> python -m venv .venv nanodjango> .venv\Scripts\activate (.venv) nanodjango> pip install --upgrade pip (.venv) nanodjango> pip install -r requirements.txt ``` -------------------------------- ### Creating Migrations Manually (Bash) Source: https://github.com/radiac/nanodjango/blob/main/docs/tutorial.rst Shows how to use the `nanodjango manage` command to run a specific Django management command (`makemigrations counter`) against the nanodjango script file, allowing manual control over migration creation without running the application. ```bash nanodjango manage counter.py makemigrations counter ``` -------------------------------- ### Installing nanodjango with pip Source: https://github.com/radiac/nanodjango/blob/main/README.md Installs the nanodjango Python package and its dependencies using the pip package manager. This is the first step to setting up and using nanodjango for single-file Django development. ```Shell pip install nanodjango ``` -------------------------------- ### Running Project Tests - Bash Source: https://github.com/radiac/nanodjango/blob/main/docs/contributing.rst Installs dependencies specifically required for running tests from 'tests/requirements.txt' and then executes the test suite using pytest. This is a crucial step before submitting contributions to ensure code quality. ```bash (.venv) nanodjango$ pip install -r tests/requirements.txt (.venv) nanodjango$ pytest ``` -------------------------------- ### Running Script Manually with pip and Python (Shell) Source: https://github.com/radiac/nanodjango/blob/main/README.md Shows an alternative method to run the standalone nanodjango script by first manually installing its dependencies using `pip install nanodjango` and then executing the script directly with the standard `python` command. ```Shell pip install nanodjango ``` ```Shell python script.py ``` -------------------------------- ### Serving in Production Mode (Bash) Source: https://github.com/radiac/nanodjango/blob/main/docs/tutorial.rst Provides the command-line instruction to run the nanodjango script (`counter.py`) in production mode using the built-in `serve` command. This command automatically applies production-ready configurations like disabling debug and using a suitable WSGI/ASGI server. ```bash nanodjango serve counter.py ``` -------------------------------- ### Customizing Admin URL (Python) Source: https://github.com/radiac/nanodjango/blob/main/docs/tutorial.rst Shows how to set a custom URL path for the Django admin site by providing the `ADMIN_URL` setting as a keyword argument when initializing the `nanodjango` app instance. ```python app = Django(ADMIN_URL="admin/") ``` -------------------------------- ### Verifying Git Remote Configuration - Bash Source: https://github.com/radiac/nanodjango/blob/main/docs/contributing.rst Displays the configured remotes and their URLs (fetch and push) for both 'origin' (your fork) and 'upstream' (the main repository), along with the configured remote for the 'main' branch. Use this to confirm the remote setup is correct. ```bash nanodjango$ git remote -v origin git@github.com:/nanodjango.git (fetch) origin git@github.com:/nanodjango.git (push) upstream https://github.com/radiac/nanodjango (fetch) upstream git@github.com:/nanodjango.git (push) nanodjango$ git config branch.main.remote upstream ``` -------------------------------- ### Example Django Ninja API Code (Python) Source: https://github.com/radiac/nanodjango/blob/main/docs/convert_plugin.rst Demonstrates typical `django-ninja` code defining an API instance and a decorated endpoint function, which serves as the target for the converter plugin to process correctly. ```Python from ninja import NinjaAPI api = NinjaAPI() @api.get("/add") def add(request, a: int, b: int): return {"result": a + b} app.route("api/", include=api.urls) ``` -------------------------------- ### Using a Model in a View (Python) Source: https://github.com/radiac/nanodjango/blob/main/docs/tutorial.rst Demonstrates incorporating Django ORM operations within a view function defined in nanodjango. The example shows creating new instances (`CountLog.objects.create()`) and querying the count (`CountLog.objects.count()`) of a previously defined model. ```python @app.route("/") def count(request): CountLog.objects.create() return f"

Number of page loads: {CountLog.objects.count()}

" ``` -------------------------------- ### Running a nanodjango Application Locally (Shell) Source: https://github.com/radiac/nanodjango/blob/main/README.md Executes the specified single-file nanodjango application (`counter.py`) using the `nanodjango run` command. This command handles creating migrations, setting up the database, and starting a development server for local testing. ```Shell nanodjango run counter.py ``` -------------------------------- ### Running Nanodjango with PEP 723 Comments (Python) Source: https://github.com/radiac/nanodjango/blob/main/docs/usage.rst Demonstrates adding a PEP 723 script metadata block to a nanodjango script to declare its dependencies. This allows tools like `uv run` or `pipx run` to automatically create a virtual environment and install `nanodjango` before executing the script. Includes the standard `app.run()` call. ```python # /// script # dependencies = ["nanodjango"] # /// from nanodjango import Django app = Django() ... if __name__ == "__main__": app.run() ``` -------------------------------- ### Using nanodjango convert with Options (Shell) Source: https://github.com/radiac/nanodjango/blob/main/docs/convert.rst Provides a practical example of executing the `nanodjango convert` command with common options. It shows how to convert a specific nanodjango file (`counter.py`), specify the target directory (`project`), set a custom project name (`tracker`), and enable the `--delete` flag to handle existing directories. ```Shell nanodjango convert counter.py project --name=tracker --delete ``` -------------------------------- ### Running Standalone Script with uv or pipx (Shell) Source: https://github.com/radiac/nanodjango/blob/main/README.md Demonstrates executing the standalone nanodjango script (`./script.py`) directly using package managers `uv` or `pipx`. These tools read the PEP 723 metadata to automatically handle dependency installation and script execution. ```Shell # Run with uv uv run ./script.py ``` ```Shell # or with pipx pipx run ./script.py ``` -------------------------------- ### Running Nanodjango App Directly (Python) Source: https://github.com/radiac/nanodjango/blob/main/docs/usage.rst Shows how to initialize a nanodjango `Django` application instance and run it directly from within the Python script using the standard `if __name__ == "__main__":` block. Calling `app.run()` launches the Django development server for convenience. Requires the `nanodjango` library installed. ```python from nanodjango import Django app = Django() ... if __name__ == "__main__": app.run() ``` -------------------------------- ### Defining a View with @app.route (Python) Source: https://github.com/radiac/nanodjango/blob/main/docs/tutorial.rst Shows how to define a standard Django view function and associate it with a specific URL path (`/`) using the `@app.route` decorator provided by the `nanodjango` app instance. The decorated function receives a standard Django `request` object. ```python @app.route("/") def count(request): ... ``` -------------------------------- ### Defining a Django Model (Python) Source: https://github.com/radiac/nanodjango/blob/main/docs/tutorial.rst Demonstrates how to define a standard Django model class (`CountLog`) within the single nanodjango file. It emphasizes that model definitions must appear after the `app = Django()` initialization line. ```python from django.db import models app = Django() class CountLog(models.Model): timestamp = models.DateTimeField(auto_now_add=True) ``` -------------------------------- ### Initializing Nanodjango Before Direct Ninja Import - Python Source: https://github.com/radiac/nanodjango/blob/main/docs/apis.rst This snippet provides an example of the correct import order when choosing to import `Django Ninja` directly instead of using the `app.ninja` helper. It shows initializing the nanodjango `app = Django()` instance *before* importing and configuring `NinjaAPI` to avoid import order issues. ```python from nanodjango import Django app = Django() from ninja import NinjaAPI api = NinjaAPI() @api.get("/add") def add(request): CountLog.objects.create() app.route("api/", include=api.urls) ``` -------------------------------- ### Running nanodjango in Production Mode (Shell) Source: https://github.com/radiac/nanodjango/blob/main/README.md Starts the specified nanodjango application (`counter.py`) using the `nanodjango serve` command. This command runs the app with production defaults, typically using gunicorn or uvicorn and disabling development settings like `DEBUG`. ```Shell nanodjango serve counter.py ``` -------------------------------- ### Customizing Admin Registration (@app.admin) (Python) Source: https://github.com/radiac/nanodjango/blob/main/docs/tutorial.rst Illustrates how to pass keyword arguments to the `@app.admin` decorator to configure the `ModelAdmin` options for the registered model. This allows customization of how the model appears and behaves within the Django admin interface, such as specifying fields to display. ```python @app.admin( list_display=["id", "timestamp"], readonly_fields=["timestamp"], ) class CountLog(models.Model): ... ``` -------------------------------- ### Rendering Template in nanodjango View (Python) Source: https://github.com/radiac/nanodjango/blob/main/docs/templates.rst This snippet provides an example of a nanodjango view function (`index`) that uses the `app.render` shortcut to render the `index.html` template. The `app.render` method simplifies returning an HTTP response by rendering the template with the provided context (`{"books": Book.objects.all()}`) and returning the result. It requires a defined template (either in a file or in `app.templates`) and a request object. ```python @app.route("/") def index(request): return app.render(request, "index.html", {"books": Book.objects.all()}) app.templates = { "index.html" : """ {% extends \"base.html\" %} {% block content %}

There are {{ books.count }} books:

{% for book in books %}

{{ book.title }}

{% endfor %} {% endblock %} """, ... } ``` -------------------------------- ### Defining API Endpoint with @app.api (Python) Source: https://github.com/radiac/nanodjango/blob/main/docs/tutorial.rst Illustrates how to create an API endpoint using the `Django Ninja` library integration in nanodjango. The `@app.api` decorator registers a `NinjaAPI` instance, and methods like `.get()` are used to define specific API routes and HTTP methods. ```python @app.api.get("/hello") def hello(request): return {"message": "Hello!"} ``` -------------------------------- ### Executing Python Script Directly (Bash) Source: https://github.com/radiac/nanodjango/blob/main/docs/usage.rst Simple shell command to execute a Python script that has been configured to run a nanodjango application directly via `app.run()`. This launches the development server defined within the script itself. Requires Python to be installed and the script to be executable. ```bash python hello.py ``` -------------------------------- ### Registering Model with Admin (@app.admin) (Python) Source: https://github.com/radiac/nanodjango/blob/main/docs/tutorial.rst Shows the basic usage of the `@app.admin` decorator applied to a Django model class (`CountLog`). This decorator automatically registers the model with the built-in Django admin site, making it manageable via the admin interface. ```python @app.admin class CountLog(models.Model): ... ``` -------------------------------- ### Adding Script Entry Point for Direct Execution (Python) Source: https://github.com/radiac/nanodjango/blob/main/README.md Adds a standard Python `if __name__ == "__main__":` block to the nanodjango script that calls `app.run()`. This makes the script directly executable using the `python` interpreter after dependencies have been manually installed. ```Python if __name__ == "__main__": app.run() ``` -------------------------------- ### Using app.ninja for Advanced Ninja Features - Python Source: https://github.com/radiac/nanodjango/blob/main/docs/apis.rst This example illustrates how to access and use additional Django Ninja features like defining schemas and handling file uploads (`app.ninja.UploadedFile`, `app.ninja.File`) through the convenient `app.ninja` attribute in nanodjango, without needing direct imports. ```python class Item(app.ninja.Schema): foo: str bar: float @app.api.post('/do_something') def do_something( request, item: Item, file: app.ninja.UploadedFile = app.ninja.File(..) ): ... ``` -------------------------------- ### Defining API Endpoint using app.api and Schema - Python Source: https://github.com/radiac/nanodjango/blob/main/docs/apis.rst This snippet demonstrates how to define a data schema using `app.ninja.Schema` and create a GET API endpoint `/add` using the `@app.api.get` decorator provided by nanodjango's built-in Django Ninja integration. It shows how to accept parameters with type hints. ```python class Item(app.ninja.Schema): foo: str bar: float @app.api.get("/add") def add(request, a: int, b: int): return {"result": a + b} ``` -------------------------------- ### Adding PEP 723 Inline Script Metadata (Python) Source: https://github.com/radiac/nanodjango/blob/main/README.md Includes inline script metadata at the top of the Python file formatted according to PEP 723. This metadata block is used by tools like `uv` or `pipx` to identify and install necessary dependencies (`nanodjango`) for running the script directly. ```Python # /// script # dependencies = ["nanodjango"] # /// ``` -------------------------------- ### Defining Nanodjango Plugin Entry Point (setup.py) Source: https://github.com/radiac/nanodjango/blob/main/docs/convert_plugin.rst Shows the required `entry_points` configuration in a traditional `setup.py` file to allow `nanodjango` to automatically discover converter plugins packaged with a library. ```Python setup( ... entry_points={ "nanodjango": [ "myproject = myproject.nanodjango" ] }, ) ``` -------------------------------- ### Defining Nanodjango Plugin Entry Point (pyproject.toml) Source: https://github.com/radiac/nanodjango/blob/main/docs/convert_plugin.rst Shows the configuration in a `pyproject.toml` file under the `[project.entry-points.nanodjango]` section to enable automatic discovery of converter plugins. ```TOML [project.entry-points.nanodjango] myproject = "myproject.nanodjango" ``` -------------------------------- ### Using Local Nanodjango Converter Plugin (Shell) Source: https://github.com/radiac/nanodjango/blob/main/docs/convert_plugin.rst Demonstrates how to run the `nanodjango convert` command, specifying a local plugin file path using the `--plugin` argument. Useful for testing or private plugins. ```Shell nanodjango app.py convert project --name=example --plugin=myplugin.py ``` -------------------------------- ### Running Nanodjango with Uvicorn (Bash) Source: https://github.com/radiac/nanodjango/blob/main/docs/usage.rst Command to serve a nanodjango application using the Uvicorn ASGI server. It specifies the application entry point (`counter:app`). This method is necessary when the nanodjango app includes asynchronous views or API endpoints. ```bash uvicorn counter:app ``` -------------------------------- ### Showing Full Syntax of nanodjango convert (Shell) Source: https://github.com/radiac/nanodjango/blob/main/docs/convert.rst Presents the complete command-line syntax for the `nanodjango convert` command. It outlines the required arguments for the source script (``) and target path (``), along with optional flags like `--name` to specify the new project name and `--delete` to force overwrite. ```Shell nanodjango convert --name= --delete ``` -------------------------------- ### Running Default Management Command (runserver) with nanodjango (Bash) Source: https://github.com/radiac/nanodjango/blob/main/docs/usage.rst Demonstrates using the `nanodjango manage` command without explicitly specifying a management command. In this case, `nanodjango` defaults to running `runserver 0:8000` on the provided script, offering a shortcut for launching the development server. ```bash nanodjango manage counter.py ``` -------------------------------- ### Converting Nanodjango App to Django Project (Shell) Source: https://github.com/radiac/nanodjango/blob/main/docs/convert.rst Demonstrates the basic usage of the `nanodjango convert` command line tool. This command converts a single-file nanodjango application (`counter.py`) into a standard Django project structure within a specified target directory (`path/to/new/project`). It is the simplest form of the conversion command. ```Shell nanodjango convert counter.py path/to/new/project ``` -------------------------------- ### Running Nanodjango Production Server (Bash) Source: https://github.com/radiac/nanodjango/blob/main/docs/usage.rst Command to run a nanodjango script for production deployment. It utilizes Gunicorn (or Uvicorn for async) and serves static files via Whitenoise after collecting them into `settings.STATIC_ROOT`. This command does not serve media files; a separate web server is recommended. ```bash nanodjango serve script.py [host:port] ``` -------------------------------- ### Running Django Management Commands with nanodjango (Bash) Source: https://github.com/radiac/nanodjango/blob/main/docs/usage.rst Shows the general syntax for using the `nanodjango manage` command. This command allows users to execute standard Django management commands (like `migrate`, `runserver`, etc.) against their nanodjango application script. It requires specifying the script file and the desired command. ```bash nanodjango manage [] ``` -------------------------------- ### Running Nanodjango with Gunicorn (Bash) Source: https://github.com/radiac/nanodjango/blob/main/docs/usage.rst Command to serve a nanodjango application using the Gunicorn WSGI server. It specifies the application entry point (`counter:app`) and can optionally set the number of worker processes (`-w 4`). This method is suitable for production deployment of synchronous nanodjango apps. ```bash gunicorn -w 4 counter:app ``` -------------------------------- ### Demonstrating Settings Not Configured Error with Ninja Python Source: https://github.com/radiac/nanodjango/blob/main/docs/troubleshooting.rst Shows the incorrect order of operations where the `ninja` library is imported before the `Django` class is instantiated and configured with settings. This results in an `ImproperlyConfigured` error because `ninja` attempts to access settings during import time. Requires `nanodjango` and `ninja`. ```Python from nanodjango import Django from ninja import NinjaAPI # will fail here, settings are not configured app = Django() api = NinjaAPI() ``` -------------------------------- ### Running Nanodjango Development Server (Bash) Source: https://github.com/radiac/nanodjango/blob/main/docs/usage.rst Command to run a nanodjango script in development mode. It uses Django's development server (`runserver` or `uvicorn` for async) and serves static and media files using Django's `static` views. Requires the `nanodjango` command-line tool. ```bash nanodjango run script.py [host:port] ``` -------------------------------- ### Running makemigrations Management Command with nanodjango (Bash) Source: https://github.com/radiac/nanodjango/blob/main/docs/usage.rst Shows how to execute the standard Django `makemigrations` management command using the `nanodjango manage` tool. This command creates new database migration files based on model changes. It requires specifying the application name, which `nanodjango` derives from the script filename. ```bash nanodjango manage counter.py makemigrations counter ``` -------------------------------- ### Converting Single-File App to Full Django Project (Shell) Source: https://github.com/radiac/nanodjango/blob/main/README.md Transforms a single-file nanodjango application (`counter.py`) into a standard, multi-directory Django project structure. The command specifies the output directory (`path/to/site`) and optionally sets the project name using the `--name` flag. ```Shell nanodjango convert counter.py path/to/site --name=counter ``` -------------------------------- ### Serving nanodjango with Gunicorn or Uvicorn (Shell) Source: https://github.com/radiac/nanodjango/blob/main/README.md Provides alternative methods to run the nanodjango application in production using standard Python WSGI (`gunicorn`) or ASGI (`uvicorn`) servers. The application object (`counter:app`) is directly passed to the server command. ```Shell gunicorn -w 4 counter:app ``` ```Shell uvicorn counter:app ``` -------------------------------- ### Executing PEP 723 Script with uv run (Bash) Source: https://github.com/radiac/nanodjango/blob/main/docs/usage.rst Command to execute a Python script containing PEP 723 metadata using the `uv run` tool. This command automatically handles setting up a temporary environment with the specified dependencies (like `nanodjango`) and then runs the script. ```bash uv run ./script.py ``` -------------------------------- ### Running migrate Management Command with nanodjango (Bash) Source: https://github.com/radiac/nanodjango/blob/main/docs/usage.rst Demonstrates how to execute the standard Django `migrate` management command on a nanodjango application script using the `nanodjango manage` tool. This command applies database migrations defined within the application. Requires the database settings to be correctly configured. ```bash nanodjango manage counter.py migrate ``` -------------------------------- ### Registering Found NinjaAPI Instances (Python) Source: https://github.com/radiac/nanodjango/blob/main/docs/convert_plugin.rst Extends the logic for finding `NinjaAPI` assignments, iterating through targets, using `collect_references`, adding to the `Resolver` and a tracking set, and unparsing/storing the source code. ```Python from nanodjango.convert.utils import collect_references ... if (...): for target in obj_ast.targets: if isinstance(target, ast.Name): name = target.id api_objs.add(name) references = collect_references(obj_ast) resolver.add(name, references) src = ast.unparse(obj_ast) code.append(src) ``` -------------------------------- ### Running Django Management Commands via nanodjango (Shell) Source: https://github.com/radiac/nanodjango/blob/main/README.md Illustrates how to execute standard Django management commands like `check`, `makemigrations`, and `runserver` for a nanodjango application. Commands are invoked by prefixing them with `nanodjango manage` followed by the script file path. ```Shell nanodjango manage script.py check ``` ```Shell nanodjango manage script.py makemigrations script ``` ```Shell nanodjango manage script.py runserver 0:8000 ``` -------------------------------- ### Defining Basic Route with path() - Python Source: https://github.com/radiac/nanodjango/blob/main/docs/views.rst Shows how to use the `@app.route` decorator on a Python function to register a simple URL path (`/`) with the nanodjango application instance (`app`). The decorated function serves as the view handler. ```python @app.route("/") def index(request): ... ``` -------------------------------- ### Running runserver Management Command Explicitly with nanodjango (Bash) Source: https://github.com/radiac/nanodjango/blob/main/docs/usage.rst Shows the explicit command to run the `runserver` management command on a nanodjango script using the `nanodjango manage` tool. This command launches the development server on the specified host and port, providing the same functionality as the default command. ```bash nanodjango manage counter.py runserver 0:8000 ``` -------------------------------- ### Initializing Django App Python Source: https://github.com/radiac/nanodjango/blob/main/docs/settings.rst This snippet demonstrates how to initialize a nanodjango application instance by passing custom Django settings directly to the Django object constructor. It shows overriding ALLOWED_HOSTS, reading SECRET_KEY from an environment variable, and setting DEBUG. Dependencies include the `nanodjango.Django` class and potentially the `os` module for `os.environ`. ```Python app = Django( ALLOWED_HOSTS=["localhost", "127.0.0.1", "my.example.com"], SECRET_KEY=os.environ["SECRET_KEY"], DEBUG=False, ) ``` -------------------------------- ### Finding NinjaAPI Instances in Plugin (Python) Source: https://github.com/radiac/nanodjango/blob/main/docs/convert_plugin.rst Shows the Python code within a converter plugin's hook to iterate through the app's global AST nodes, identify assignments to `NinjaAPI` instances, and initialize the resolver and tracking set. ```Python import ast from nanodjango.convert.plugin import ConverterPlugin, Resolver class NinjaConverter(ConverterPlugin): def build_app_models_done(self, converter: Converter): resolver = Resolver(converter, ".api") api_objs = set() code = [] for obj_ast in converter.ast.body: if ( isinstance(obj_ast, ast.Assign) and isinstance(obj_ast.value, ast.Call) and isinstance(obj_ast.value.func, ast.Name) and obj_ast.value.func.id == "NinjaAPI" ): # We've found a NinjaAPI instance ``` -------------------------------- ### Running Nanodjango ASGI Handler with Uvicorn (Bash) Source: https://github.com/radiac/nanodjango/blob/main/docs/usage.rst Command to explicitly serve the ASGI handler of a nanodjango application using Uvicorn. This is used to force the use of the ASGI interface, ensuring async capabilities are utilized, overriding nanodjango's automatic detection. ```bash uvicorn counter:app.asgi ``` -------------------------------- ### Executing PEP 723 Script with pipx run (Bash) Source: https://github.com/radiac/nanodjango/blob/main/docs/usage.rst Command to execute a Python script containing PEP 723 metadata using the `pipx run` tool. Similar to `uv run`, this command creates a temporary environment with dependencies and runs the script, providing an easy way to test or run standalone scripts. ```bash pipx run ./script.py ``` -------------------------------- ### Initial Nanodjango Converter Plugin Structure (Python) Source: https://github.com/radiac/nanodjango/blob/main/docs/convert_plugin.rst Defines the basic structure for a `nanodjango` converter plugin by subclassing `ConverterPlugin` and implementing the `build_app_models_done` hook to run logic after models are processed. ```Python class NinjaConverter(ConverterPlugin): def build_app_models_done(self, converter: Converter): ... ``` -------------------------------- ### Defining Django View with HttpResponse Type Hint (Python) Source: https://github.com/radiac/nanodjango/blob/main/docs/convert.rst Illustrates a Python view function within a nanodjango context that will be converted to Django. The function `redirect` is decorated with `@app.route` and importantly includes a return type hint (`-> HttpResponseRedirect`) to inform the converter that an `HttpResponse` subclass is explicitly returned, preventing the addition of automatic decorators. ```Python @app.route("/author/") def redirect(request) -> HttpResponseRedirect: return HttpResponseRedirect("https://radiac.net/") ``` -------------------------------- ### Defining Async API View with app.api.get - Python Source: https://github.com/radiac/nanodjango/blob/main/docs/views.rst Demonstrates defining an asynchronous view function using `async def` and registering it with `@app.api.get`. This enables the view to perform awaitable operations, showcasing nanodjango's support for async views, potentially integrated with an API framework. ```python @app.api.get("/async") async def api_async(request): sleep = random.randint(1, 5) await asyncio.sleep(sleep) return { "saying": f"Hello world, async endpoint. You waited {sleep} seconds.", "type": "async", } ``` -------------------------------- ### Fixing Settings Not Configured Error in Nanodjango Python Source: https://github.com/radiac/nanodjango/blob/main/docs/troubleshooting.rst Corrects the settings configuration issue by instantiating the `Django` class and providing settings *before* importing libraries like `ninja` that access settings during their import phase. This ensures settings are available when needed, resolving the `ImproperlyConfigured` error. Requires `nanodjango` and `ninja`. ```Python from nanodjango import Django app = Django() from ninja import NinjaAPI # will fail here, settings are not configured api = NinjaAPI() ``` -------------------------------- ### Writing Generated API File (Python) Source: https://github.com/radiac/nanodjango/blob/main/docs/convert_plugin.rst This Python method snippet demonstrates how to write the generated `api.py` file. It first checks if any API objects (`api_objs`) were found; if not, it returns early. Otherwise, it uses the provided `converter` object's `write_file` method to write to `api.py` in the app's path, combining source code generated by a `resolver` with collected code snippets. ```Python def build_app_models_done(self, converter: Converter): ... if not api_objs: return converter.write_file( converter.app_path / "api.py", resolver.gen_src(), "\n".join(code), ) ``` -------------------------------- ### Including External URL Configurations - Python Source: https://github.com/radiac/nanodjango/blob/main/docs/views.rst Shows how to integrate URL patterns from other Django applications or third-party frameworks (like Django Ninja or fastview) into the nanodjango application's routing by calling `app.route` with the desired path prefix and the external urlconf's patterns. ```python # Add a django-ninja API from ninja import NinjaAPI api = NinjaAPI() app.route("api/", api.urls) # Add a django-fastview viewgroup from fastview.viewgroups.auth import AuthViewGroup app.route("accounts/", AuthViewGroup().include()) ``` -------------------------------- ### Finding Decorated Endpoint Functions (Python) Source: https://github.com/radiac/nanodjango/blob/main/docs/convert_plugin.rst Adds logic to the plugin hook to look for `ast.FunctionDef` nodes, identify decorators using `get_decorators`, check if they reference known `NinjaAPI` instances, and register the function and its references with the `Resolver`. ```Python from nanodjango.convert.utils import get_decorators ... elif isinstance(obj_ast, ast.FunctionDef): decorators = get_decorators(obj_ast) for decorator in decorators: # If it's been used as ``@decorator()`` then there's a function call # - if it was ``@decorator`` there won't. Standardise to make it # easier to work with if isinstance(decorator, ast.Call): decorator = decorator.func if ( isinstance(decorator, ast.Attribute) and isinstance(decorator.value, ast.Name) and decorator.value.id in api_objs ): resolver.add_object(obj_ast.name) references = collect_references(obj_ast) resolver.add(name, references) src = ast.unparse(obj_ast) code.append(src) ``` -------------------------------- ### Include Base Dependency File - Requirements Source: https://github.com/radiac/nanodjango/blob/main/tests/requirements.txt This line specifies that dependencies listed in the file located at ../requirements.txt relative to the current file should be included as requirements. This is a standard practice in pip requirement files (requirements.txt) to compose dependency lists from multiple files. ```Requirements -r ../requirements.txt ``` -------------------------------- ### List Pytest Testing Dependencies - Requirements Source: https://github.com/radiac/nanodjango/blob/main/tests/requirements.txt These lines list the specific packages required for running tests in this project. pytest is the testing framework, and pytest-cov is a plugin for test coverage analysis. These are typically listed as development dependencies. ```Requirements pytest pytest-cov ``` -------------------------------- ### Running Nanodjango WSGI Handler with Gunicorn (Bash) Source: https://github.com/radiac/nanodjango/blob/main/docs/usage.rst Command to explicitly serve the WSGI handler of a nanodjango application using Gunicorn. This is used to force the use of the WSGI interface, even if the app might contain async views, overriding nanodjango's automatic detection. ```bash gunicorn counter:app.wsgi ``` -------------------------------- ### Defining Templates in nanodjango via Dict Assignment (Python) Source: https://github.com/radiac/nanodjango/blob/main/docs/templates.rst This snippet illustrates an alternative method for defining multiple templates in memory by assigning a dictionary containing all template paths and content directly to `app.templates`. This method is equivalent to multiple key assignments and is often cleaner for defining several templates at once. It also uses Django's `locmem` loader and supports template inheritance. ```python app.templates = { "base.html": """ {% block content %}{% endblock %} " """, "myview/hello.html": """ {% extends \"base.html\" %} {% block content %}Hello{% endblock %} """, } ``` -------------------------------- ### Cloning nanodjango Fork (HTTPS) - Bash Source: https://github.com/radiac/nanodjango/blob/main/docs/contributing.rst Clones your personal fork of the nanodjango project from GitHub using the HTTPS protocol. Use this as an alternative if cloning via SSH is not possible or preferred. ```bash $ git clone https://github.com//nanodjango.git ``` -------------------------------- ### Configuring Git Remotes for Contribution - Bash Source: https://github.com/radiac/nanodjango/blob/main/docs/contributing.rst Sets up 'upstream' remote pointing to the official nanodjango repository and configures git to pull from 'upstream/main' but push changes to your 'origin' fork. This facilitates synchronizing with the main project while working on your own changes. ```bash $ cd nanodjango nanodjango$ git remote add upstream https://github.com/radiac/nanodjango nanodjango$ git config branch.main.remote upstream nanodjango$ git remote set-url --push upstream git@github.com:/nanodjango.git ``` -------------------------------- ### Defining Templates in nanodjango via Key Assignment (Python) Source: https://github.com/radiac/nanodjango/blob/main/docs/templates.rst This snippet demonstrates how to define template content directly within the nanodjango application script by assigning multiline strings to specific keys in the `app.templates` dictionary. Each key represents the template's relative path and filename, allowing templates to be defined in memory rather than separate files. This approach uses Django's `locmem` template loader and is suitable for defining individual templates. ```python app.templates["base.html"] = """ {% block content %}{% endblock %} " """ app.templates["myview/hello.html"] = "{% block content %}Hello{% endblock %}" ``` -------------------------------- ### Enabling Admin with ADMIN_URL in nanodjango Python Source: https://github.com/radiac/nanodjango/blob/main/docs/admin.rst Shows how to explicitly enable and configure the Django admin site URL by providing the `ADMIN_URL` setting when initializing the `Django` app instance in `nanodjango`. This ensures the admin is accessible at the specified path, especially if no models are decorated with `@app.admin`. ```Python app = Django(ADMIN_URL="admin/") ``` -------------------------------- ### Defining a Single-File nanodjango Application (Python) Source: https://github.com/radiac/nanodjango/blob/main/README.md Creates a minimal nanodjango application in a single Python file (`counter.py`). It includes a Django model (`CountLog`) registered with the admin, a standard function view (`count`), a Django Ninja API endpoint (`add`), and an async view (`slow`), demonstrating core nanodjango features. ```Python from django.db import models from nanodjango import Django app = Django() @app.admin class CountLog(models.Model): # Standard Django model, registered with the admin site timestamp = models.DateTimeField(auto_now_add=True) @app.route("/") def count(request): # Standard Django function view CountLog.objects.create() return f"

Number of page loads: {CountLog.objects.count()}

" @app.api.get("/add") def add(request): # Django Ninja API support built in CountLog.objects.create() return {"count": CountLog.objects.count()} @app.route("/slow/") async def slow(request): import asyncio await asyncio.sleep(10) return "Async views supported" ``` -------------------------------- ### Cloning nanodjango Fork (SSH) - Bash Source: https://github.com/radiac/nanodjango/blob/main/docs/contributing.rst Clones your personal fork of the nanodjango project from GitHub using the SSH protocol. This is typically the first step after forking the repository. ```bash $ git clone git@github.com:/nanodjango.git ``` -------------------------------- ### Returning Plain String from View - Python Source: https://github.com/radiac/nanodjango/blob/main/docs/views.rst Demonstrates a nanodjango view function defined with `@app.route` that simply returns a plain string. For convenience, nanodjango automatically handles the conversion of this string into an appropriate `HttpResponse` before sending it back to the client. ```python @app.route("/") def hello_world(request): return "

Hello, World!

" ``` -------------------------------- ### Defining Route with Path Converters - Python Source: https://github.com/radiac/nanodjango/blob/main/docs/views.rst Demonstrates defining a route using the `@app.route` decorator with path converters (``, ``) to capture URL segments and pass them as arguments to the view function. This utilizes Django's standard `path` functionality behind the scenes. ```python @app.route("articles////") def article_detail(request, year, month, slug): ... ``` -------------------------------- ### Applying Additional Decorators to View - Python Source: https://github.com/radiac/nanodjango/blob/main/docs/views.rst Illustrates how to apply other standard Django decorators (such as authentication or permission decorators) to a nanodjango view function. It is important that the `@app.route` decorator is always placed directly above the function definition. ```python @app.route("/") @login_required def count(request): return "Hello world" ``` -------------------------------- ### Registering Model with Standard Django Admin in nanodjango Python Source: https://github.com/radiac/nanodjango/blob/main/docs/admin.rst Illustrates how to use the standard Django approach (`admin.site.register`) to register a model (`CountLog`) with a custom `ModelAdmin` class (`CountLogAdmin`). This method provides full flexibility for complex customizations that are not possible via the `@app.admin` decorator arguments. Requires importing the `admin` module from `django.contrib` and defining a class inheriting from `admin.ModelAdmin`. ```Python from django.contrib import admin class CountLogAdmin(admin.ModelAdmin): list_display = ["id", "timestamp"] readonly_fields = ["timestamp"] admin.site.register(CountLog, CountLogAdmin) ``` -------------------------------- ### Merging Upstream Changes to Fork - Bash Source: https://github.com/radiac/nanodjango/blob/main/docs/contributing.rst Checks out the local 'main' branch, fetches the latest changes from the 'upstream' remote, merges the 'upstream/main' branch into the local 'main' branch, and finally pushes the updated 'main' branch to the 'origin' fork. This process keeps your personal fork synchronized with the main project. ```bash $ git checkout main $ git fetch upstream $ git merge upstream/main $ git push origin main ``` -------------------------------- ### Returning HttpResponse from View - Python Source: https://github.com/radiac/nanodjango/blob/main/docs/views.rst Shows a nanodjango view function defined with `@app.route` that explicitly creates and returns a `django.http.HttpResponse` object. This is the standard Django practice and provides full control over the response; using a return type hint is recommended for clarity. ```python @app.route("/") def hello_world(request) -> HttpResponse: return HttpResponse("

Hello, World!

") ``` -------------------------------- ### Registering Model with app.admin Decorator in nanodjango Python Source: https://github.com/radiac/nanodjango/blob/main/docs/admin.rst Demonstrates the primary way to register a Django model (`CountLog`) with the admin site in `nanodjango` using the `@app.admin` decorator placed above the model class definition. This provides a minimal default registration, making the model available in the admin interface. Requires defining a Django model inheriting from `models.Model`. ```Python @app.admin class CountLog(models.Model): timestamp = models.DateTimeField(auto_now_add=True) ``` -------------------------------- ### Defining Route with Regular Expression (re_path) - Python Source: https://github.com/radiac/nanodjango/blob/main/docs/views.rst Illustrates using the `@app.route` decorator with `re=True` to define a route using a regular expression pattern. This corresponds to Django's `re_path` and allows for more complex pattern matching; captured groups are typically passed as keyword arguments to the view function. ```python @app.route("authors/(?P[a-z]{3,})/", re=True) def author_detail(request, slug): ... ``` -------------------------------- ### Customizing ModelAdmin via app.admin Decorator in nanodjango Python Source: https://github.com/radiac/nanodjango/blob/main/docs/admin.rst Shows how to pass common `ModelAdmin` attributes like `list_display` and `readonly_fields` directly as keyword arguments to the `@app.admin()` decorator when registering a model. This allows basic customization of how the model's list view and form are displayed and edited within the Django admin without creating a separate `ModelAdmin` class. Requires defining a Django model inheriting from `models.Model`. ```Python @app.admin(list_display=["id", "timestamp"], readonly_fields=["timestamp"]) class CountLog(models.Model): timestamp = models.DateTimeField(auto_now_add=True) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.