What is the role of __init__.py in a Django app directory, and why is it necessary for the framework to recognize it?
Last updated
__init__.py marks a directory as a Python package, which is what lets Django (and Python's import system) import the app's modules like models and views. Without it, the folder is just a directory, not an importable module.
Primary role: Tells Python "this directory is a package," enabling dotted imports like
from blog.models import Post.Why Django needs it: Django imports apps by name from
INSTALLED_APPS; the import only resolves if the directory is a package.It can hold code too: Optionally used to set
default_app_config(older Django) or run package-level initialization.Nuance: Python 3 supports namespace packages without it, but Django apps conventionally and reliably use an explicit
__init__.py.
- https://www.geeksforgeeks.org/python/django-interview-questions/
- https://foysalff.medium.com/12-advanced-django-interview-questions-for-experienced-developers-dbe654e21a45
- https://www.careers360.com/courses-certifications/articles/django-interview-questions-and-answers
- https://www.interviewbit.com/django-interview-questions/
- https://www.youtube.com/watch?v=OuBUUkQfBYM
- https://www.placementpreparation.io/blog/django-interview-questions-for-freshers/