Transform any Python package into a Django Project and Application.
This approach allows you to use Django's ORM, migrations, and commands without the need for the typical Django project boilerplate.
- Copy the
django_manage.py
file to your package folder. - Run
python -m my_package.django_manage
to access the full list of available Django commands.
To use Django's ORM, define your models in the my_package/models.py
file. Be sure to
import the django_manage
module before importing your models to properly initialize the
environment.
from . import django_manage # noqa: F401, I001
from .models import MyModel
print(MyModel.objects.count())
Once you've defined or updated your models, you can use Django's migration system to handle database schema changes.
- Create new migrations for your models:
mkdir my_package/migrations python -m my_package.django_manage makemigrations
- Apply the generated migrations to update your database schema:
python -m my_package.django_manage migrate
- Inspect the migration history or view pending migrations with:
python -m my_package.django_manage showmigrations
- Add
ROOT_URLCONF
,SECRET_KEY
andALLOWED_HOSTS
to the settings:conf.settings.configure( ..., ROOT_URLCONF="django_manage", SECRET_KEY=..., ALLOWED_HOSTS=..., ) django.setup() ...
- Add
urlpatterns
to thedjango_manage
module:... django.setup() urlpatterns = [ path("", lambda request: HttpResponse("Hello!")), ] def main(): ...
- Test the server:
python -m my_package.django_manage runserver