### Installing Local Dependencies for IDE Support Source: https://wilfredinni.github.io/django-starter-template/environment_setup This command installs project dependencies locally. This is crucial for IDEs to provide features like IntelliSense and code completion, even when the main application is running within Docker containers. ```bash uv sync ``` -------------------------------- ### Copying .env.example to .env Source: https://wilfredinni.github.io/django-starter-template/environment_setup This command demonstrates how to create the actual `.env` file from the example template. This is a standard shell command used to initialize the project's environment configuration. ```bash cp .env.example .env ``` -------------------------------- ### Example Environment Variables Configuration (.env.example) Source: https://wilfredinni.github.io/django-starter-template/environment_setup This snippet shows the structure and example values for environment variables in the `.env.example` file. It covers basic configuration, email settings, and security parameters. This file serves as a template for the actual `.env` file. ```dotenv # -------------------------------------------------------------------------------- # ⚡ Basic Config: for development and testing. # -------------------------------------------------------------------------------- DEBUG=True DATABASE_URL=postgres://postgres:postgres@localhost:5432/postgres DJANGO_SECRET_KEY=django-insecure-wlgjuo53y49%-4y5(!%ksylle_ud%b=7%__@9hh+@$d%_^y3s! # -------------------------------------------------------------------------------- # 📧 Email Config: optional and can be copied if needed. # -------------------------------------------------------------------------------- EMAIL_HOST=smtp.gmail.com EMAIL_USE_TLS=True EMAIL_PORT=587 EMAIL_HOST_USER=user@user.com EMAIL_HOST_PASSWORD=myverystrongpassword # -------------------------------------------------------------------------------- # 🔐 Security Config: for production or testing the production settings locally. # -------------------------------------------------------------------------------- ALLOWED_HOSTS=mysite.com,mysite2.com CORS_ALLOWED_ORIGINS=mysite.com,mysite2.com SENTRY_DSN=https://examplePublicKey@o0.ingest.sentry.io/0 ``` -------------------------------- ### Install Local Dependencies for IDE Support Source: https://wilfredinni.github.io/django-starter-template/development This command installs project dependencies locally using `uv`, a fast Python package installer and virtual environment manager. This enables IDE features like code completion, IntelliSense, import resolution, type checking, linting, and formatting by providing the IDE with a local environment to analyze. ```bash uv sync --all-extras ``` -------------------------------- ### Example Production .env File for Django Source: https://wilfredinni.github.io/django-starter-template/environment_setup This snippet demonstrates a typical `.env` file structure for a Django production environment. It includes common settings like debug mode, secret key, allowed hosts, database URL, CORS origins, Sentry DSN, and email configuration. Sensitive information should be managed securely by the deployment platform. ```dotenv DEBUG=False DJANGO_SECRET_KEY=your_very_long_and_secure_production_secret_key ALLOWED_HOSTS=api.yourdomain.com,www.yourdomain.com DATABASE_URL=postgres://user:password@db.yourdomain.com:5432/prod_db CORS_ALLOWED_ORIGINS=https://www.yourdomain.com,https://app.yourdomain.com SENTRY_DSN=https://your_sentry_public_key@o0.ingest.sentry.io/0 EMAIL_HOST=smtp.sendgrid.net EMAIL_USE_TLS=True EMAIL_PORT=587 EMAIL_HOST_USER=apikey EMAIL_HOST_PASSWORD=your_sendgrid_api_key ``` -------------------------------- ### Start and Manage Docker Services with Make Source: https://wilfredinni.github.io/django-starter-template/development These commands use the Makefile to manage Docker Compose services. They simplify starting, stopping, building, and viewing the status of all project services (database, Redis, Django backend, Celery worker, and beat scheduler). ```bash make up make down make build make rebuild make ps ``` -------------------------------- ### GET /core/fire-task/ Source: https://wilfredinni.github.io/django-starter-template/core_endpoints Triggers a sample Celery task in the background, useful for testing Celery setup and task execution. ```APIDOC ## GET /core/fire-task/ ### Description This endpoint triggers a sample Celery task in the background. It's useful for testing the Celery setup and task execution. ### Method GET ### Endpoint /core/fire-task/ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200 OK) - **task** (string) - Confirmation that the task has been successfully initiated. #### Response Example ```json { "task": "Task fired" } ``` ``` -------------------------------- ### Django Installed Applications Configuration Source: https://wilfredinni.github.io/django-starter-template/settings Defines the list of Django applications enabled in the project. This includes built-in Django apps, third-party libraries like whitenoise and rest_framework, and local project applications. ```python INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'whitenoise', 'rest_framework', 'knox', 'drf_spectacular', 'apps.users', 'apps.core', ] ``` -------------------------------- ### User Creation API Endpoint Request and Response (JSON) Source: https://wilfredinni.github.io/django-starter-template/authentication Example of a POST request to the user creation endpoint, including the required JSON body with email and password fields. It also shows example success and error responses, illustrating successful user creation, password mismatch, existing email, and invalid password scenarios. ```json { "email": "user@example.com", "password": "complexpassword123", "password2": "complexpassword123" } ``` ```json { "email": "user@example.com" } ``` ```json { "password": [ "Passwords do not match." ] } ``` ```json { "email": [ "This email is already registered." ] } ``` ```json { "password": [ "This password is too short. It must contain at least 8 characters." ] } ``` ```json { "detail": "Authentication credentials were not provided." } ``` -------------------------------- ### GET /core/ping/ Source: https://wilfredinni.github.io/django-starter-template/core_endpoints A simple endpoint to verify server operational status. It returns a 'pong' response to indicate liveness. ```APIDOC ## GET /core/ping/ ### Description A simple endpoint designed to verify that the server is operational and responsive. ### Method GET ### Endpoint /core/ping/ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200 OK) - **ping** (string) - Indicates a successful response with the value 'pong'. #### Response Example ```json { "ping": "pong" } ``` ``` -------------------------------- ### Refactor Prompt for GitHub Copilot Source: https://wilfredinni.github.io/django-starter-template/ai_tools/copilot This prompt instructs GitHub Copilot to refactor existing code by focusing on performance, security, maintainability, and readability. It requires a structured analysis of the code, providing rationale and examples for suggested improvements. ```markdown As a senior software engineer, analyze the provided code and suggest specific refactoring improvements focusing on these key aspects: 1. Performance: - Identify algorithmic inefficiencies - Optimize resource usage and memory management - Suggest caching strategies where applicable - Highlight potential bottlenecks 2. Security: - Review for common vulnerabilities (OWASP Top 10) - Ensure proper input validation - Verify authentication and authorization - Check for secure data handling 3. Maintainability: - Apply SOLID principles - Improve code organization and structure - Reduce technical debt - Enhance modularity and reusability 4. Readability: - Follow language-specific style guides - Apply consistent naming conventions - Add meaningful comments and documentation - Break down complex logic into smaller functions For each suggested improvement: - Explain the rationale - Provide a code example - Highlight potential trade-offs - Consider the impact on existing functionality Please provide the code you want to refactor, and specify any constraints or requirements specific to your project's context. ``` -------------------------------- ### Feature Prompt for GitHub Copilot Source: https://wilfredinni.github.io/django-starter-template/ai_tools/copilot This prompt guides GitHub Copilot to plan and implement new features by detailing the feature's overview, impact analysis, implementation plan, code, and integration strategy. It emphasizes adherence to project guidelines, clean architecture, and SOLID principles. ```markdown As a professional developer, analyze and implement a new feature in the codebase following these guidelines: 1. Feature Overview - Describe the feature's core functionality and purpose - List specific requirements and acceptance criteria - Define expected inputs and outputs - Specify performance targets and constraints 2. Impact Analysis - Identify affected components and dependencies - Evaluate performance implications - Assess security considerations - Document potential risks and mitigations 3. Implementation Plan - Break down the feature into atomic tasks - Specify interfaces and data structures - Define error handling and edge cases - List required test scenarios 4. Code Implementation - Provide code examples for each component - Include inline documentation - Follow project coding standards - Implement necessary unit tests 5. Integration Strategy - Outline deployment steps - Specify configuration changes - Document API modifications - Define rollback procedures Include benchmark results, security review findings, and maintainability metrics for each implemented component. Prioritize clean architecture and SOLID principles. ``` -------------------------------- ### Escaping Special Characters in .env for Docker Compose Source: https://wilfredinni.github.io/django-starter-template/environment_setup This example illustrates the correct way to escape special characters, specifically the dollar sign (`$`), within environment variable values when using Docker Compose. Incorrect escaping can lead to Docker Compose misinterpreting values as variables. ```dotenv # Incorrect - Docker Compose treats $d as a variable DJANGO_SECRET_KEY=django-insecure-abc@$d123 # Correct - Escape $ with $$ DJANGO_SECRET_KEY=django-insecure-abc@$$d123 ``` -------------------------------- ### Django Template Engine Configuration Source: https://wilfredinni.github.io/django-starter-template/settings Configures Django's template engine, including the backend, directories for template files, and options for context processors and built-ins. ```python TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [root_path('templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], 'builtins': [ # Register built-in template tags and filters here ], }, }, ] ``` -------------------------------- ### Manage Asynchronous Tasks with Celery (Docker & Local) Source: https://wilfredinni.github.io/django-starter-template/development Commands for managing Celery workers and beat schedulers for asynchronous task processing. Includes instructions for using 'make' and 'docker compose' for logs, as well as starting worker and beat processes locally. ```bash # Using make (recommended) make logs-worker make logs-beat # Using docker compose docker compose logs -f worker docker compose logs -f beat ``` ```bash # Start the Celery worker: celery -A conf worker -l info # Start the Celery beat scheduler: celery -A conf beat -l info ``` -------------------------------- ### Centralized Schema Definitions (Python) Source: https://wilfredinni.github.io/django-starter-template/auto_documentation Defines reusable schema components like error responses and common examples in dedicated `schema.py` files. This promotes reusability and keeps view logic clean. It uses `drf_spectacular.utils.inline_serializer` and `OpenApiExample` to define structures and examples for API responses. ```python from drf_spectacular.utils import OpenApiExample, inline_serializer from rest_framework import serializers ErrorResponseSerializer = inline_serializer( name="ErrorResponse", fields={ "detail": serializers.CharField(read_only=True), "code": serializers.CharField(read_only=True, required=False), }, ) UNAUTHORIZED_EXAMPLES = [ OpenApiExample( "Unauthorized", value={"detail": "Authentication credentials were not provided."}, status_codes=["401"], ), # ... other examples ] ``` -------------------------------- ### Configure Environment Variables with .env File Source: https://wilfredinni.github.io/django-starter-template/development This command copies an example environment file to a new file named `.env`. This `.env` file is used by Docker Compose to define environment variables for the services, allowing for local customization of settings like database credentials or secret keys. ```bash cp .env.example .env ``` -------------------------------- ### Initialize Environment Variables with django-environ Source: https://wilfredinni.github.io/django-starter-template/settings This snippet demonstrates how to initialize `django-environ` to load environment variables from a `.env` file. It sets up the environment reader and defines the project's root path for resolving relative paths. Ensure `.env` file is present in the project root. ```python import environ env = environ.Env() root_path = environ.Path(__file__) - 2 env.read_env(str(root_path.path(".env"))) ``` -------------------------------- ### Retrieve User Profile (GET) Source: https://wilfredinni.github.io/django-starter-template/authentication Retrieves the profile information (email, first name, last name) of the currently authenticated user. Requires token authentication and returns a 401 Unauthorized error if credentials are invalid. ```json { "email": "user@example.com", "first_name": "John", "last_name": "Doe" } ``` ```json { "detail": "Authentication credentials were not provided." } ``` -------------------------------- ### Django Middleware Configuration Source: https://wilfredinni.github.io/django-starter-template/settings Specifies the middleware classes that process requests and responses globally. The order is critical for security, static file handling, sessions, CORS, CSRF, and authentication. ```python MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'apps.core.middleware.RequestIDMiddleware', ] ``` -------------------------------- ### Django ALLOWED_HOSTS Configuration Source: https://wilfredinni.github.io/django-starter-template/settings Sets the ALLOWED_HOSTS list, which specifies the host/domain names Django can serve. It's loaded from the ALLOWED_HOSTS environment variable and defaults to ['*']. In production, specify exact domain names for security. ```python ALLOWED_HOSTS = env.list("ALLOWED_HOSTS", default=["*"]) ``` -------------------------------- ### Ping API Endpoint - Django Source: https://wilfredinni.github.io/django-starter-template/core_endpoints A simple GET endpoint to check server responsiveness. It returns a JSON object {'ping': 'pong'} upon successful execution. This is useful for health checks and verifying server operational status. ```Python from django.http import JsonResponse def ping_view(request): return JsonResponse({"ping": "pong"}) ``` -------------------------------- ### Seed Database with Sample Data (Make & Docker) Source: https://wilfredinni.github.io/django-starter-template/development Instructions for populating the database with sample data using a management command. Supports seeding with a specified number of users, creating a superuser, and cleaning existing data. Recommended usage is via 'make'. ```bash # Seed with 20 users + superuser, cleaning existing data make seed ``` ```bash # Basic seeding with default options (creates 10 users) docker compose exec backend python manage.py seed # Create a specific number of users docker compose exec backend python manage.py seed --users 20 # Create a superuser (admin@admin.com:admin) docker compose exec backend python manage.py seed --superuser # Clean existing data before seeding docker compose exec backend python manage.py seed --clean # Combine options docker compose exec backend python manage.py seed --users 50 --superuser --clean ``` -------------------------------- ### Run Tests and Generate Coverage Reports (Make & Docker) Source: https://wilfredinni.github.io/django-starter-template/development Commands for executing the test suite and generating code coverage reports using both 'make' utility and 'docker compose'. This includes running all tests, running tests with coverage, and generating an HTML coverage report. ```bash make test ``` ```bash make test-cov ``` ```bash make test-html ``` ```bash # Run all tests docker compose exec backend pytest # Run tests with coverage docker compose exec backend pytest --cov # Generate HTML coverage report docker compose exec backend pytest --cov --cov-report=html ``` -------------------------------- ### Run Django Commands and Testing with Make Source: https://wilfredinni.github.io/django-starter-template/development This set of Makefile commands facilitates interaction with the Django application and its testing framework. It allows opening a Django shell, running the test suite, executing tests with coverage reporting, and viewing logs for different services. ```bash make shell make test make test-cov make logs make logs-worker make logs-beat ``` -------------------------------- ### Create User Source: https://wilfredinni.github.io/django-starter-template/authentication Allows for the registration of a new user account. Requires email and password confirmation. ```APIDOC ## POST /auth/create/ ### Description This endpoint allows for the registration of a new user account. ### Method POST ### Endpoint /auth/create/ ### Parameters #### Request Body - **email** (string) - Required - The user's unique email address. - **password** (string) - Required - The user's chosen password. - **password2** (string) - Required - Confirmation of the user's chosen password (must match `password`). ### Request Example ```json { "email": "user@example.com", "password": "complexpassword123", "password2": "complexpassword123" } ``` ### Response #### Success Response (201 Created) - **email** (string) - The email of the newly created user. #### Response Example ```json { "email": "user@example.com" } ``` #### Error Response (400 Bad Request) - **Passwords do not match:** ```json { "password": [ "Passwords do not match." ] } ``` - **Email already registered:** ```json { "email": [ "This email is already registered." ] } ``` - **Invalid password (e.g., too short, common password):** ```json { "password": [ "This password is too short. It must contain at least 8 characters." ] } ``` #### Error Response (401 Unauthorized) - **Detail** (string) - Authentication credentials were not provided. ```json { "detail": "Authentication credentials were not provided." } ``` ``` -------------------------------- ### Manage Project Dependencies with Make Source: https://wilfredinni.github.io/django-starter-template/development These Makefile commands assist in managing project dependencies. They provide shortcuts for updating all dependencies, adding a new package, and removing an existing one, ensuring the project's dependencies are kept up-to-date. ```bash make update-deps make add-dep "pkg=name" make remove-dep "pkg=name" ``` -------------------------------- ### Django SECRET_KEY Configuration Source: https://wilfredinni.github.io/django-starter-template/settings Configures the SECRET_KEY for Django applications, loaded from the DJANGO_SECRET_KEY environment variable. This key is crucial for cryptographic signing and must be kept secret, never hardcoded. ```python SECRET_KEY = env("DJANGO_SECRET_KEY") ``` -------------------------------- ### Django Database Configuration Source: https://wilfredinni.github.io/django-starter-template/settings Configures the default database connection for Django using the DATABASE_URL environment variable, parsed by django-environ. DJANGO_DATABASE_URL holds the connection string, and DATABASES uses it for the default connection. ```python DJANGO_DATABASE_URL = env.db("DATABASE_URL") DATABASES = {"default": DJANGO_DATABASE_URL} ``` -------------------------------- ### Perform Maintenance Tasks with Make Source: https://wilfredinni.github.io/django-starter-template/development These Makefile commands are for maintaining the Docker environment and project state. They include stopping services and removing associated volumes, as well as cleaning up unused Docker resources to free up disk space. ```bash make clean make prune ``` -------------------------------- ### Login User with Email and Password (POST) Source: https://wilfredinni.github.io/django-starter-template/authentication Authenticates a user by their email and password, returning an authentication token upon success. Handles invalid credentials and missing fields with appropriate error responses. ```json { "email": "user@example.com", "password": "complexpassword123" } ``` ```json { "expiry": "2025-07-09T12:00:00Z", "token": "your-auth-token", "user": { "email": "user@example.com", "first_name": "", "last_name": "" } } ``` ```json { "detail": "Unable to log in with provided credentials." } ``` ```json { "email": [ "This field is required." ], "password": [ "This field is required." ] } ``` -------------------------------- ### Update Anonymous User Rate Limit (Django Settings) Source: https://wilfredinni.github.io/django-starter-template/rate_limiting Shows how to modify the default rate limit for anonymous users in `conf/settings.py`. This example changes the limit from 100 requests per day to 50 requests per hour. ```python # In conf/settings.py REST_FRAMEWORK = { # ... "DEFAULT_THROTTLE_RATES": { "user": "1000/day", "anon": "50/hour", # Changed from 100/day "user_login": "5/minute", }, } ``` -------------------------------- ### Manage Django Database with Make Source: https://wilfredinni.github.io/django-starter-template/development These Makefile commands streamline common Django database operations. They include running pending migrations, creating new migration files based on model changes, and seeding the database with initial test data. ```bash make migrate make makemigrations make seed ``` -------------------------------- ### View Logs and Rebuild Containers with Docker Compose Source: https://wilfredinni.github.io/django-starter-template/development These direct Docker Compose commands allow viewing the logs of the backend service in a follow mode and rebuilding the containers. Rebuilding is typically done after dependency changes or when updates to the Docker image are needed. ```bash docker compose logs -f backend docker compose up --build ``` -------------------------------- ### Execute Django Commands Directly with Docker Compose Source: https://wilfredinni.github.io/django-starter-template/development This section shows how to execute Django management commands directly using `docker compose exec`. It covers essential tasks like running migrations, creating migrations, creating a superuser, and opening the Django shell. ```bash docker compose exec backend python manage.py migrate docker compose exec backend python manage.py makemigrations docker compose exec backend python manage.py createsuperuser docker compose exec backend python manage.py shell ``` -------------------------------- ### Fire Celery Task API Endpoint - Django Source: https://wilfredinni.github.io/django-starter-template/core_endpoints A GET endpoint that triggers a sample Celery task in the background. It returns a JSON confirmation {'task': 'Task fired'} upon successful initiation. This endpoint is valuable for testing the Celery integration and ensuring background tasks are processed correctly. ```Python from django.http import JsonResponse from .tasks import sample_celery_task # Assuming sample_celery_task is defined in tasks.py def fire_task_view(request): sample_celery_task.delay() return JsonResponse({"task": "Task fired"}) ``` -------------------------------- ### User Authentication API Source: https://wilfredinni.github.io/django-starter-template/authentication Endpoints for user login, logout, and profile management. ```APIDOC ## POST /auth/login/ ### Description This endpoint authenticates a user and issues an authentication token. ### Method POST ### Endpoint /auth/login/ ### Parameters #### Request Body - **email** (string) - Required - The user's registered email address. - **password** (string) - Required - The user's password. ### Request Example ```json { "email": "user@example.com", "password": "complexpassword123" } ``` ### Response #### Success Response (200 OK) - **expiry** (string) - The expiration timestamp of the token. - **token** (string) - The authentication token to be used in subsequent requests. - **user** (object) - A dictionary containing basic user profile information. - **email** (string) - The user's email address. - **first_name** (string) - The user's first name. - **last_name** (string) - The user's last name. #### Response Example ```json { "expiry": "2025-07-09T12:00:00Z", "token": "your-auth-token", "user": { "email": "user@example.com", "first_name": "", "last_name": "" } } ``` #### Error Response (400 Bad Request) - **detail** (string) - Unable to log in with provided credentials. - **email** (array) - This field is required. - **password** (array) - This field is required. #### Error Example (Invalid Credentials) ```json { "detail": "Unable to log in with provided credentials." } ``` #### Error Example (Missing Fields) ```json { "email": [ "This field is required." ], "password": [ "This field is required." ] } ``` ## POST /auth/logout/ ### Description This endpoint logs out the currently authenticated user by invalidating their current authentication token. ### Method POST ### Endpoint /auth/logout/ ### Authentication Token required. ### Response #### Success Response (204 No Content) - The response will have an empty body, indicating successful token invalidation. #### Error Response (401 Unauthorized) - **detail** (string) - Authentication credentials were not provided. #### Error Example ```json { "detail": "Authentication credentials were not provided." } ``` ## POST /auth/logoutall/ ### Description This endpoint invalidates all authentication tokens for the currently authenticated user, effectively logging them out from all devices. ### Method POST ### Endpoint /auth/logoutall/ ### Authentication Token required. ### Response #### Success Response (204 No Content) - The response will have an empty body, indicating that all tokens for the user have been invalidated. #### Error Response (401 Unauthorized) - **detail** (string) - Authentication credentials were not provided. #### Error Example ```json { "detail": "Authentication credentials were not provided." } ``` ## GET /auth/profile/ ### Description Retrieves the profile of the currently authenticated user. ### Method GET ### Endpoint /auth/profile/ ### Authentication Token required. ### Response #### Success Response (200 OK) - **email** (string) - The user's email address. - **first_name** (string) - The user's first name. - **last_name** (string) - The user's last name. #### Response Example ```json { "email": "user@example.com", "first_name": "John", "last_name": "Doe" } ``` #### Error Response (401 Unauthorized) - **detail** (string) - Authentication credentials were not provided. #### Error Example ```json { "detail": "Authentication credentials were not provided." } ``` ## PUT /auth/profile/ ### Description Updates the entire profile of the currently authenticated user. All fields must be provided. ### Method PUT ### Endpoint /auth/profile/ ### Authentication Token required. ### Parameters #### Request Body - **first_name** (string) - Required - The user's first name. - **last_name** (string) - Required - The user's last name. ### Request Example ```json { "first_name": "Jane", "last_name": "Doe" } ``` ### Response #### Success Response (200 OK) - **email** (string) - The user's email address. - **first_name** (string) - The user's first name. - **last_name** (string) - The user's last name. #### Response Example ```json { "email": "user@example.com", "first_name": "Jane", "last_name": "Doe" } ``` #### Error Response (400 Bad Request) - **password** (array) - Password must be at least 8 characters long. #### Error Example ```json { "password": [ "Password must be at least 8 characters long." ] } ``` #### Error Response (401 Unauthorized) - **detail** (string) - Authentication credentials were not provided. #### Error Example ```json { "detail": "Authentication credentials were not provided." } ``` ## PATCH /auth/profile/ ### Description Partially updates the profile of the currently authenticated user. Only the fields to be updated need to be provided. ### Method PATCH ### Endpoint /auth/profile/ ### Authentication Token required. ### Parameters #### Request Body - **first_name** (string) - Optional - The user's first name. - **last_name** (string) - Optional - The user's last name. ### Request Example ```json { "first_name": "Jane" } ``` ### Response #### Success Response (200 OK) - **email** (string) - The user's email address. - **first_name** (string) - The user's first name. - **last_name** (string) - The user's last name. #### Response Example ```json { "email": "user@example.com", "first_name": "Jane", "last_name": "Doe" } ``` #### Error Response (401 Unauthorized) - **detail** (string) - Authentication credentials were not provided. #### Error Example ```json { "detail": "Authentication credentials were not provided." } ``` ``` -------------------------------- ### Stop Services with Docker Compose Source: https://wilfredinni.github.io/django-starter-template/development This command uses Docker Compose to stop all services defined in the `docker-compose.yml` file. It's a direct alternative to the `make down` command. ```bash docker compose down ``` -------------------------------- ### Update User Profile (PUT) Source: https://wilfredinni.github.io/django-starter-template/authentication Updates the entire profile of the currently authenticated user. All fields (first name, last name) must be provided. Returns the updated profile on success or appropriate error responses for invalid data or unauthorized access. ```json { "first_name": "Jane", "last_name": "Doe" } ``` ```json { "email": "user@example.com", "first_name": "Jane", "last_name": "Doe" } ``` ```json { "password": [ "Password must be at least 8 characters long." ] } ``` ```json { "detail": "Authentication credentials were not provided." } ``` -------------------------------- ### Swagger UI URL Configuration (Python) Source: https://wilfredinni.github.io/django-starter-template/auto_documentation Configures the endpoints for serving the OpenAPI schema and the interactive Swagger UI in `conf/urls.py`. It conditionally adds these routes when `settings.DEBUG` is true, making the documentation accessible via `/api/schema/` and `/api/schema/swagger-ui/`. ```python from drf_spectacular.views import SpectacularAPIView, SpectacularSwaggerView urlpatterns = [ # ... other urls ] if settings.DEBUG: urlpatterns += [ path("api/schema/", SpectacularAPIView.as_view(), name="schema"), path( "api/schema/swagger-ui/", SpectacularSwaggerView.as_view(url_name="schema"), name="swagger-ui", ), ] ``` -------------------------------- ### Global drf-spectacular Settings (Python) Source: https://wilfredinni.github.io/django-starter-template/auto_documentation Configures global settings for `drf-spectacular` within the `SPECTACULAR_SETTINGS` dictionary in `conf/settings.py`. This allows for setting basic API metadata such as title, description, and version, along with other operational flags like `SERVE_INCLUDE_SCHEMA`. ```python SPECTACULAR_SETTINGS = { "TITLE": "Django Starter Template", "DESCRIPTION": "A comprehensive starting point for your new API with Django and DRF", "VERSION": "0.1.0", "SERVE_INCLUDE_SCHEMA": False, } ``` -------------------------------- ### Running Tests with Coverage Report (Docker Compose) Source: https://wilfredinni.github.io/django-starter-template/testing Runs tests and generates a code coverage report using Docker Compose. It includes options to display coverage summary in the terminal and generate an HTML report for detailed analysis. ```bash docker compose exec backend pytest --cov --cov-report=html ```