title: What is Django?
permalink: what-is-django
tags:
- django
- python
date created: Wednesday, February 7th 2024, 9:47:53 am
date modified: Tuesday, May 13th 2025, 8:23:11 am
Collect static files in a central place after configuring the STATIC_ROOT
.
python manage.py collectstatic --noinput
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))
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."))
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}")