Django

Django is a Python framework that makes it easier to build web apps quickly and with less code.

Docs

Models

Static files

Collect static files in a central place after configuring the STATIC_ROOT.

python manage.py collectstatic --noinput

Commands

Example

Important

Make sure your app is registered with INSTALLED_APPS.

settings.py

INSTALLED_APPS = [
    "your_app.apps.YourAppConfig",
    #...

your_app/management/commands/your_command.py

from django.core.management.base import BaseCommand, CommandError

class Command(BaseCommand):
    help = 'Describes what your command does.'

    def add_arguments(self, parser):
        # Optional: Add command-line arguments here, if needed
        parser.add_argument('sample_arg', type=int)

    def handle(self, *args, **options):
        sample_arg = options['sample_arg']
        # Your logic here
        self.stdout.write(self.style.SUCCESS('Successfully did something with %s' % sample_arg))

Print

Write messages to stdout or stderr.

# Default style
self.stdout.write(message)

# Styled as errors
errors = []
write(self.style.ERROR(f"Encountered {len(errors)} errors."))

Wait for models to load

When issuing Django commands, an app's models may have yet to load. If this is not handled, it will err.

To ensure dependent models load first, place imports within the AppConfig's ready function.

For example, I have an app named feedback. It depends on the employee app and its models. Its app config should look like this:

feedback/app.py

from django.apps import AppConfig

class FeedbackConfig(AppConfig):
    name = 'feedback'
    verbose_name = 'Django Feedback Bundle'

    def ready(self):
        from my.package.models.employee__employee import Employee

You can now use the app in a command.

feedback/management/commands/validate_user.py

from django.core.management.base import BaseCommand
from cisco.feedback.survey import validate_survey_participant

class Command(BaseCommand):
    help = "Can the user take this survey?"

    def add_arguments(self, parser):
        parser.add_argument("username", type=str, help="Enter a username")

    def handle(self, *args, **options):
        def write(message):
            """
            Write a message to stdout.
            """
            self.stdout.write(message)

        username = options.get("username") or DEFAULT_USERNAME
        should_take_survey = validate_survey_participant(username, contact_type)

        write(f"Can the user take this survey? {should_take_survey}")

Resources

Django
Interactive graph
On this page
Docs
Models
Static files
Commands
Example
Print
Wait for models to load
Resources