Repository: pydanny/dj-notebook Branch: main Commit: ce5711baba41 Files: 72 Total size: 205.5 KB Directory structure: gitextract_oq4ufw3w/ ├── .github/ │ ├── FUNDING.yml │ ├── ISSUE_TEMPLATE/ │ │ ├── bug_report.md │ │ └── feature_request.md │ └── workflows/ │ ├── contributing.yml │ ├── python-ci.yml │ └── python-publish.yml ├── .gitignore ├── .readthedocs.yml ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── Makefile ├── README.md ├── docs/ │ ├── activation.md │ ├── changelog.md │ ├── contributing.md │ ├── index.md │ ├── installation.md │ ├── pycharm.md │ ├── reference/ │ │ ├── index.md │ │ └── plus.md │ ├── releasing.md │ └── usage.ipynb ├── mkdocs.yml ├── pyproject.toml ├── src/ │ └── dj_notebook/ │ ├── __init__.py │ ├── config_helper.py │ └── shell_plus.py ├── tests/ │ ├── __init__.py │ ├── config_debug_false.py │ ├── config_test_harness.py │ ├── django_test_project/ │ │ ├── book_outlet/ │ │ │ ├── __init__.py │ │ │ ├── admin.py │ │ │ ├── apps.py │ │ │ ├── migrations/ │ │ │ │ ├── 0001_initial.py │ │ │ │ ├── 0002_book_author_book_is_bestselling_alter_book_rating.py │ │ │ │ ├── 0003_book_slug.py │ │ │ │ ├── 0004_author_alter_book_slug_alter_book_author.py │ │ │ │ ├── 0005_alter_book_author.py │ │ │ │ ├── 0006_address_author_address.py │ │ │ │ ├── 0007_country_alter_address_options_and_more.py │ │ │ │ └── __init__.py │ │ │ ├── models.py │ │ │ ├── templates/ │ │ │ │ └── book_outlet/ │ │ │ │ ├── base.html │ │ │ │ ├── book_detail.html │ │ │ │ └── index.html │ │ │ ├── tests.py │ │ │ ├── urls.py │ │ │ └── views.py │ │ ├── book_store/ │ │ │ ├── __init__.py │ │ │ ├── asgi.py │ │ │ ├── settings.py │ │ │ ├── urls.py │ │ │ └── wsgi.py │ │ ├── data.sqlite3 │ │ ├── example_fk.ipynb │ │ ├── example_long_form.ipynb │ │ ├── example_mermaid.ipynb │ │ ├── example_print.ipynb │ │ ├── example_short_form.ipynb │ │ └── manage.py │ ├── env.django_settings_module │ ├── fake_manage_alias_environ.py │ ├── fake_manage_fully_qualified.py │ ├── fake_manage_import_environ.py │ ├── fake_other_environ_and_real_environ_setdefault.py │ ├── fake_other_environ_setdefault.py │ ├── sample.csv │ ├── test_config_helper.py │ └── test_dj_notebook.py └── utils/ └── update_changelog.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/FUNDING.yml ================================================ --- # These are supported funding model platforms github: [pydanny] patreon: # Replace with a single Patreon username open_collective: # Replace with a single Open Collective username ko_fi: # Replace with a single Ko-fi username tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry liberapay: # Replace with a single Liberapay username issuehunt: # Replace with a single IssueHunt username otechie: # Replace with a single Otechie username lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] ================================================ FILE: .github/ISSUE_TEMPLATE/bug_report.md ================================================ --- name: Bug report about: Create a report to help us improve title: '' labels: '' assignees: '' --- **Describe the bug** A clear and concise description of what the bug is. **To Reproduce** Steps to reproduce the behavior: 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' 4. See error **Expected behavior** A clear and concise description of what you expected to happen. **Screenshots** If applicable, add screenshots to help explain your problem. **Desktop (please complete the following information):** - OS: [e.g. iOS] - Browser [e.g. chrome, safari] - Version [e.g. 22] **Smartphone (please complete the following information):** - Device: [e.g. iPhone6] - OS: [e.g. iOS8.1] - Browser [e.g. stock browser, safari] - Version [e.g. 22] **Additional context** Add any other context about the problem here. ================================================ FILE: .github/ISSUE_TEMPLATE/feature_request.md ================================================ --- name: Feature request about: Suggest an idea for this project title: '' labels: '' assignees: '' --- **Is your feature request related to a problem? Please describe.** A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] **Describe the solution you'd like** A clear and concise description of what you want to happen. **Describe alternatives you've considered** A clear and concise description of any alternative solutions or features you've considered. **Additional context** Add any other context or screenshots about the feature request here. ================================================ FILE: .github/workflows/contributing.yml ================================================ --- name: Contributing on: push: branches: [main] jobs: contrib-readme-job: runs-on: ubuntu-latest name: A job to automate contrib in readme steps: - name: Contribute List uses: akhilmhdh/contributors-readme-action@v2.3.6 env: GITHUB_TOKEN: ${{ secrets.REPO_TOKEN }} ================================================ FILE: .github/workflows/python-ci.yml ================================================ --- name: CI on: [push] jobs: build: runs-on: ubuntu-latest strategy: matrix: python-version: ['3.10', '3.11', '3.12'] steps: - uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v4 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | python -m pip install uv uv pip install -p ${{ matrix.python-version }} '.[dev]' - name: Lint with ruff and black run: | # stop the build if there are linting errors make lint - name: Test with pytest run: |- pytest ================================================ FILE: .github/workflows/python-publish.yml ================================================ --- # This workflow will upload a Python Package using Twine when a release is created # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python#publishing-to-package-registries # This workflow uses actions that are not certified by GitHub. # They are provided by a third-party and are governed by # separate terms of service, privacy policy, and support # documentation. name: Publish Python Package on: release: types: [published] permissions: contents: read jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Set up Python uses: actions/setup-python@v3 with: python-version: 3.x - name: Install dependencies run: | pip install uv uv pip install -p 3.12 build - name: Build package run: | rm -rf dist python -m build - name: Publish package uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29 with: user: __token__ password: ${{ secrets.PYPI_API_TOKEN }} ================================================ FILE: .gitignore ================================================ # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ share/python-wheels/ *.egg-info/ .installed.cfg *.egg MANIFEST # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .nox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover *.py,cover .hypothesis/ .pytest_cache/ cover/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py db.sqlite3 db.sqlite3-journal # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder .pybuilder/ target/ # Jupyter Notebook .ipynb_checkpoints # IPython profile_default/ ipython_config.py # pyenv # For a library or package, you might want to ignore these files since the code is # intended to run in multiple environments; otherwise, check them in: # .python-version # pipenv # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. # However, in case of collaboration, if having platform-specific dependencies or dependencies # having no cross-platform support, pipenv may install dependencies that don't work, or not # install all needed dependencies. #Pipfile.lock # poetry # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. # This is especially recommended for binary packages to ensure reproducibility, and is more # commonly ignored for libraries. # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control #poetry.lock # pdm # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. #pdm.lock # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it # in version control. # https://pdm.fming.dev/#use-with-ide .pdm.toml # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm __pypackages__/ # Celery stuff celerybeat-schedule celerybeat.pid # SageMath parsed files *.sage.py # Environments .env .venv env/ venv/ ENV/ env.bak/ venv.bak/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ .dmypy.json dmypy.json # Pyre type checker .pyre/ # pytype static type analyzer .pytype/ # Cython debug symbols cython_debug/ # PyCharm # JetBrains specific template is maintained in a separate JetBrains.gitignore that can # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore # and can be added to the global gitignore or merged into this file. For a more nuclear # option (not recommended) you can uncomment the following to ignore the entire idea folder. #.idea/ .hypothesis/ .vscode/ .ruff_cache/ changelog.json .idea .DS_Store ================================================ FILE: .readthedocs.yml ================================================ --- version: 2 build: os: ubuntu-22.04 tools: python: '3.10' jobs: pre_build: ["pip install '.[dev]'", mkdocs build] mkdocs: configuration: mkdocs.yml fail_on_warning: false ================================================ FILE: CHANGELOG.md ================================================ # [v0.7.0](https://github.com/pydanny/dj-notebook/releases/tag/v0.7.0) ## What's Changed - New Feature * Allow notebooks in other locations by @nmpowell in https://github.com/pydanny/dj-notebook/pull/162 ## What's Changed * Change byline by @pydanny in https://github.com/pydanny/dj-notebook/pull/144 * Add django-extensions to contributors by @pydanny in https://github.com/pydanny/dj-notebook/pull/145 * Add mkdocs include so README is the index by @pydanny in https://github.com/pydanny/dj-notebook/pull/150 * Add changelog to docs site by @pydanny in https://github.com/pydanny/dj-notebook/pull/151 * Add code reference using mkdocstrings by @pydanny in https://github.com/pydanny/dj-notebook/pull/154 * Lint the yaml and add to CI by @pydanny in https://github.com/pydanny/dj-notebook/pull/158 * Add csv_to_df function by @pydanny in https://github.com/pydanny/dj-notebook/pull/160 ## New Contributors * @nmpowell made their first contribution in https://github.com/pydanny/dj-notebook/pull/162 **Full Changelog**: https://github.com/pydanny/dj-notebook/compare/v0.6.1...v0.7.0 # [v0.6.1](https://github.com/pydanny/dj-notebook/releases/tag/v0.6.1) 2023-10-22T05:57:56Z by [@pydanny](https://github.com/pydanny) ## What's Changed Fixing borked release caused by inconsistent PyPI trove classifiers **Full Changelog**: https://github.com/pydanny/dj-notebook/compare/v0.6.0...v0.6.1 --- # [v0.6.0](https://github.com/pydanny/dj-notebook/releases/tag/v0.6.0) 2023-10-22T05:01:55Z by [@pydanny](https://github.com/pydanny) ## What's Changed * Add missing read frame example by @pydanny in https://github.com/pydanny/dj-notebook/pull/107 * Raise warning if not run in debug by @skyforest in https://github.com/pydanny/dj-notebook/pull/109 * Added chrisdev to other contributors by @specbeck in https://github.com/pydanny/dj-notebook/pull/110 * Prep for mypy by @pydanny in https://github.com/pydanny/dj-notebook/pull/112 * Use ruff for isort by @pydanny in https://github.com/pydanny/dj-notebook/pull/113 * Document how to install dj-notebook in PyCharm Professional. by @geoffbeier in https://github.com/pydanny/dj-notebook/pull/117 * Link to pycharm instructions in the docs by @pydanny in https://github.com/pydanny/dj-notebook/pull/119 * Add support for Python 3.12 by @pydanny in https://github.com/pydanny/dj-notebook/pull/116 * Remove special case for test harness from application code. by @geoffbeier in https://github.com/pydanny/dj-notebook/pull/120 * Add social cards to docs by @pydanny in https://github.com/pydanny/dj-notebook/pull/125 * Remove official support for Python 3.9 by @pydanny in https://github.com/pydanny/dj-notebook/pull/127 * improve path definitions/config discovery by @geoffbeier in https://github.com/pydanny/dj-notebook/pull/121 * Document new activate function arguments by @pydanny in https://github.com/pydanny/dj-notebook/pull/129 * fix broken link to pycharm page from info box on installation page by @geoffbeier in https://github.com/pydanny/dj-notebook/pull/131 ## New Contributors * @geoffbeier made their first contribution in https://github.com/pydanny/dj-notebook/pull/117 **Full Changelog**: https://github.com/pydanny/dj-notebook/compare/v0.5.0...v0.6.0 --- # [v0.5.0](https://github.com/pydanny/dj-notebook/releases/tag/v0.5.0) 2023-10-10T15:01:07Z by [@pydanny](https://github.com/pydanny) ## What's Changed ``` plus.model_graph(plus.User) ``` ![](https://mermaid.ink/img/Zmxvd2NoYXJ0IFRECiAgTG9nRW50cnkgLS0tIFVzZXIKICBVc2VyIC0tLSBBYnN0cmFjdFVzZXIKICBVc2VyIC0tLSBHcm91cAogIFVzZXIgLS0tIFBlcm1pc3Npb24K) * Added model graph by @pydanny in https://github.com/pydanny/dj-notebook/pull/78 and https://github.com/pydanny/dj-notebook/pull/101 * Prepping for DjangoCon sprints 2023 by @pydanny in https://github.com/pydanny/dj-notebook/pull/80 * Added first implementation of new logo by @Tejoooo in https://github.com/pydanny/dj-notebook/pull/89 * Update and Add logo to all docs by @pydanny in https://github.com/pydanny/dj-notebook/pull/91 * Implement improve graphing of models via django-schema-graph by @pydanny in https://github.com/pydanny/dj-notebook/pull/101 * In docs, corrected changed order and corrected table of contents by @pydanny in https://github.com/pydanny/dj-notebook/pull/104 ## New Contributors * @Tejoooo made their first contribution in https://github.com/pydanny/dj-notebook/pull/89 **Full Changelog**: https://github.com/pydanny/dj-notebook/compare/v0.4.0...v0.5.0 --- # [v0.4.0](https://github.com/pydanny/dj-notebook/releases/tag/v0.4.0) ## What's Changed * Add LICENSE file by @pydanny in https://github.com/pydanny/dj-notebook/pull/54 * Add issue templates by @pydanny in https://github.com/pydanny/dj-notebook/pull/55 * Update CHANGELOG.md by @pydanny in https://github.com/pydanny/dj-notebook/pull/57 * Improve display of load items by @pydanny in https://github.com/pydanny/dj-notebook/pull/59 * Add display_mermaid function by @pydanny in https://github.com/pydanny/dj-notebook/pull/61 * Optimize plus print functionality by @pydanny in https://github.com/pydanny/dj-notebook/pull/62 * Add missing attribution for prestto and evieclutton by @pydanny in https://github.com/pydanny/dj-notebook/pull/64 * docs(contributor): contributors readme action update by @pydanny in https://github.com/pydanny/dj-notebook/pull/65 * Update pyproject.toml with docs link by @specbeck in https://github.com/pydanny/dj-notebook/pull/66 ## New Contributors * @skyforest made their first contribution in https://github.com/pydanny/dj-notebook/pull/39 * @akashverma0786 made their first contribution in https://github.com/pydanny/dj-notebook/pull/49 * @specbeck made their first contribution in https://github.com/pydanny/dj-notebook/pull/66 **Full Changelog**: https://github.com/pydanny/dj-notebook/compare/v0.3.0...v0.4.0 --- # [v0.3.0](https://github.com/pydanny/dj-notebook/releases/tag/v0.3.0) 2023-10-03T17:22:45Z by [@pydanny](https://github.com/pydanny) ## New Features * Add django pandas to activate return object by @skyforest in https://github.com/pydanny/dj-notebook/pull/45 ## Other Changes * Improve the release notes by @pydanny in https://github.com/pydanny/dj-notebook/pull/26 * Add Jupyter-Book for docs by @pydanny in https://github.com/pydanny/dj-notebook/pull/28 * Fix deployment to RTD by @pydanny in https://github.com/pydanny/dj-notebook/pull/29 * Better usage instructions by @pydanny in https://github.com/pydanny/dj-notebook/pull/30 * Better usage instructions by @pydanny in https://github.com/pydanny/dj-notebook/pull/31 * Create FUNDING.yml by @pydanny in https://github.com/pydanny/dj-notebook/pull/35 * Improve test coverage by @skyforest in https://github.com/pydanny/dj-notebook/pull/39 * Add contributing segment to readme by @pydanny in https://github.com/pydanny/dj-notebook/pull/40 * docs(contributor): contributors readme action update by @pydanny in https://github.com/pydanny/dj-notebook/pull/41 * Add the name to the contributing job by @pydanny in https://github.com/pydanny/dj-notebook/pull/42 * Documented queryset to dataframe by @pydanny in https://github.com/pydanny/dj-notebook/pull/47 * Add:Content in features-list by @akashverma0786 in https://github.com/pydanny/dj-notebook/pull/49 ## New Contributors * @skyforest made their first contribution in https://github.com/pydanny/dj-notebook/pull/39 * @akashverma0786 made their first contribution in https://github.com/pydanny/dj-notebook/pull/49 **Full Changelog**: https://github.com/pydanny/dj-notebook/compare/v0.2.1...v0.3.0 --- # [v0.2.2](https://github.com/pydanny/dj-notebook/releases/tag/v0.2.2) 2023-09-26T15:24:15Z by [@pydanny](https://github.com/pydanny) ## What's Changed * Correct the release notes by @pydanny in https://github.com/pydanny/dj-notebook/pull/26 **Full Changelog**: https://github.com/pydanny/dj-notebook/compare/v0.2.1...v0.2.2 ================================================ FILE: CODE_OF_CONDUCT.md ================================================ # Contributor Covenant Code of Conduct ## Our Pledge We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ## Our Standards Examples of behavior that contributes to a positive environment for our community include: * Demonstrating empathy and kindness toward other people * Being respectful of differing opinions, viewpoints, and experiences * Giving and gracefully accepting constructive feedback * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience * Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: * The use of sexualized language or imagery, and sexual attention or advances of any kind * Trolling, insulting or derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or email address, without their explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement Responsibilities Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. ## Scope This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at . All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident. ## Enforcement Guidelines Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: ### 1. Correction **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. ### 2. Warning **Community Impact**: A violation through a single incident or series of actions. **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. ### 3. Temporary Ban **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. ### 4. Permanent Ban **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. **Consequence**: A permanent ban from any sort of public interaction within the community. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see the FAQ at https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. ================================================ FILE: CONTRIBUTING.md ================================================ Please read the [Development - Contributing](https://dj-notebook.readthedocs.io/en/latest/contributing/) guidelines in the documentation site. ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: Makefile ================================================ changelog: # Install gh cli and jq first gh api \ -H "Accept: application/vnd.github+json" \ -H "X-GitHub-Api-Version: 2022-11-28" \ /repos/pydanny/dj-notebook/releases/latest > changelog.json python utils/update_changelog.py rm changelog.json format: black . ruff check . --fix yamlfix . lint: black . ruff check . yamlfix . mypy: mypy . VERSION=v$(shell grep -m 1 version pyproject.toml | tr -s ' ' | tr -d '"' | tr -d "'" | cut -d' ' -f3) tag: echo "Tagging version $(VERSION)" git tag -a $(VERSION) -m "Creating version $(VERSION)" git push origin $(VERSION) test: coverage run -m pytest . coverage report -m coverage html install: pip install -e '.[dev]' ================================================ FILE: README.md ================================================

dj-notebook

Django + shell_plus + Jupyter notebooks made easy --- A Jupyter notebook with access to objects from the Django ORM is a powerful tool to introspect data and run ad-hoc queries. Full documentation available at [dj-notebook](https://dj-notebook.readthedocs.io/) --- ## Features The ever-growing list of features: - Easy Jupyter notebooks with Django - Built-in integration with the imported objects from django-extensions `shell_plus` - Saves the state between sessions so you don't need to remember what you did - Inheritance diagrams on any object, including ORM models - Converts any Django QuerySet to Pandas Dataframe - Handy function for displaying MermaidJS charts - Generates visual maps of model relations - Works in the browser, VSCode, PyCharm, Emacs, Vim, and more! ## Installation Use your installation tool of choice, here we use venv and pip: ```bash python -m venv venv source venv/bin/activate pip install dj_notebook ``` ## Usage First, find your project's `manage.py` file and open it. Copy whatever is being set to `DJANGO_SETTINGS_MODULE` into your clipboard. Create an ipython notebook in the same directory as `manage.py`, or another directory of your choosing. In VSCode, simply add a new `.ipynb` file. If using Jupyter Lab, use the `File -> New -> Notebook` menu option. Then in the first cell enter: ```python from dj_notebook import activate plus = activate() # If you have created your notebook in a different directory, instead do: # plus = activate(search_dir="/path/to/your/project") # If that throws an error, try one of the following: # DJANGO_SETTINGS_MODULE_VALUE aka "book_store.settings" # plus = activate("DJANGO_SETTINGS_MODULE_VALUE") # Point to location of dotenv file with Django settings # plus = activate(dotenv_file='.env') ``` In future cells, you can now load and run Django objects, including the ORM. This three line snippet should give an idea of what you can now do: ```python from django.contrib.auth import get_user_model User = get_user_model() User.objects.all() ``` ## Usage Plus But wait, it gets better! When you activated the Django environment, you instantiated a variable called 'plus'. The 'plus' variable is an object that contains everything loaded from django-extensions' `shell_plus`. Here's a demonstration, try running this snippet: ```python plus.User.objects.all() ``` We also provide a utility for introspection of classes, which can be useful in sophisticated project architectures. Running this code in a Jupyter notebook shell: ```python plus.diagram(plus.User) ``` Generates this image Here's another useful diagram: ```python plus.model_graph(plus.User) ``` ## QuerySet to Dataframe Want to convert a Django query to a Pandas Dataframe? We got you covered. ```python plus.read_frame(plus.User.objects.all()) ``` ## More things you can do! [dj-notebook official documentation](https://dj-notebook.readthedocs.io/) ## Contributors
pydanny
Daniel Roy Greenfeld
skyforest
Cody Antunez
geoffbeier
Geoff Beier
nmpowell
Nick Powell
specbeck
Saransh Sood
anna-zhydko
Anna Zhydko
Tejoooo
Tejo Kaushal
bloodearnest
Simon Davy
akashverma0786
Null
DaveParr
Dave Parr
syyong
Siew-Yit Yong
## Special thanks These are people who aren't in our formal git history but should be. - [Tom Preston](https://github.com/prestto) did seminal work on Python paths that later became the foundation of dj-notebook - [Evie Clutton](https://github.com/evieclutton) was co-author of a pull request and they don't show up in the contributor list above - [Tim Schilling](https://github.com/tim-schilling) assisted with the `model_graph` method - [Charlie Denton](https://github.com/meshy) is responsible for django-schema-graph, which we leverage as part of the `model_graph` feature - [Christopher Clarke](https://github.com/chrisdev) built `django-pandas`, which dj-notebook uses - [Stephen Moore](https://github.com/delfick) for some early work done on the internals of dj-notebook before it was open sourced. - [django-extensions](django-extensions) for providing so many useful tools over the years, and being one of the backbones of this project
prestto
Tom Preston
evieclutton
Null
tim-schilling
Tim Schilling
meshy
Charlie Denton
chrisdev
Christopher Clarke
delfick
Stephen Moore
django-extensions
Django Extensions
## Construction This package was created with [Cookiecutter](https://github.com/cookiecutter/cookiecutter) and the [simplicity](https://github.com/pydanny/simplicity) project template. ================================================ FILE: docs/activation.md ================================================ # Activation We try our best to make activating dj-notebook as easy as possible. It should be easy to do, but more complicated projects will require manipulation of paths. The goal of this page is to provide all the instruction users may need or link to external docs as necessary. !!! info "Using dj-notebook with PyCharm" If using PyCharm the [instructions described here](../pycharm) are a very useful reference. ## Auto-discovery _New in dj-notebook 0.6.0_ Create an ipython notebook in the same directory as `manage.py`. In VSCode, simply add a new `.ipynb` file. If using Jupyter Lab, use the `File -> New -> Notebook` menu option. In the first cell type the following: ```python from dj_notebook import activate plus = activate() ``` ## Specifying settings If that doesn't work, find the project's `manage.py` file and open it. Copy whatever is being set to `DJANGO_SETTINGS_MODULE` as a string argument to `activate` function like so: ```python plus = activate('book_store.settings') ``` ## Using `.env` file to specify settings _New in dj-notebook 0.6.0_ dj-notebook has support for .env files. Assuming our `.env` file is at `/me/projects/djangopackages/.env` and looks like this: ``` SECRET_KEY=TopSecretValueHere DEBUG=True DJANGO_SETTINGS_MODULE=book_store.settings ``` Then we can pass in that file in this manner: ```python plus = activate(dotenv_file='/me/projects/djangopackages/.env') ``` ## Advanced: Modifying the Path This advanced technique is when you want to activate dj-notebook in a different directory from the Django project. For example, in dj-notebook the [usage](./usage) page is completely seperate: ``` docs └── usage.ipynb tests/django_test_project └── manage.py ``` To address that, in the `docs/usage.ipynb` file we modify the path to include `django_test_project` so dj-notebook can find with a simple `activate()` call: ```python import pathlib import sys here = pathlib.Path(".").parent PROJECT_ROOT = (here / ".." / "tests" / "django_test_project").resolve() sys.path.insert(0, str(PROJECT_ROOT)) ``` !!! note For the sake of clarity, the above code is not visible in dj-notebook's rendered [usage](./usage) instructions. This is a hidden cell, so look in the [unrendered usage.ipynb file](https://github.com/pydanny/dj-notebook/blob/main/docs/usage.ipynb). ================================================ FILE: docs/changelog.md ================================================ # Changelog {% include-markdown "../CHANGELOG.md" start="" end="" heading-offset=1 %} ================================================ FILE: docs/contributing.md ================================================ # Contributing ## Git workflow * Fork the repository * Make your changes in your fork * Open a pull request to upstream repository - main branch ## Development Install the package in editable mode with test dependencies: ```bash pip install -e '.[test]' ``` Code away! ### Standards dj-notebook follows these standards: - Styleguide: [PEP-8](https://peps.python.org/pep-0008/) - Code of Conduct: [Contributor Covenant](https://www.contributor-covenant.org) - Boring Technology for Packaging: setuptools and build ### Code quality Linting and formatting is done with Black and Ruff: ```bash make lint ``` ### Testing ```bash make test ``` --- ## Advanced Odds are you won't need these things. ### Building the project locally Go to the project root ```bash pip install --upgrade build python -m build ``` Test the project, forcing reinstall if necessary ```bash pip install dist/*.whl --force-reinstall ``` ================================================ FILE: docs/index.md ================================================ # Home {% include-markdown "../README.md" start="" end="" %} ================================================ FILE: docs/installation.md ================================================ # Installation Use your installation tool of choice, here we use venv and pip: ```bash python -m venv venv source venv/bin/activate pip install dj-notebook ``` !!! info "Using dj-notebook with PyCharm" PyCharm users need to take a few extra steps described [here](../pycharm). ================================================ FILE: docs/pycharm.md ================================================ # Using dj-notebook with PyCharm PyCharm Professional has built-in integration for Jupyter notebooks. This integration works well with dj-notebook once your jupyter and dj-notebook are added to your existing Django project's virtual environment. ## Quick Start 1. Open your existing django project in pycharm. 2. Make sure that pycharm's interpreter is configured for your project's virtual environment. 3. Add dj-notebook and jupyter to that virtual environment. 4. Create a new notebook and load your django settings in the first cell. 5. Execute that cell to launch the Jupyter server. ## Adding dj-notebook to your Virtual Environment ![PyCharm Interpreter Menu](img/pycharm/interpreter_menu.png) Once pycharm has loaded your django project, you can inspect the virtual environment used by the project's interpreter by using the interpreter menu in the lower right corner of the project window. Click on the current interpreter (1) then choose "Interpreter Settings..." to to confirm the location of the virtual environment and see which packages are loaded there. If jupyter and dj-notebook are not already installed, you can add them from the IDE by clicking the add button then searching for dj-notebook: ![PyCharm - Add package](img/pycharm/add_package.png) Then click "Install Package": ![PyCharm - Install dj-notebook](img/pycharm/install_dj-notebook.png) ## Using dj-notebook Within PyCharm's Integrated Notebook View Once dj-notebook is installed, you can create a new notebook from within the project explorer: ![PyCharm - Create new notebook](img/pycharm/create_notebook.png) In the new notebook, when you execute your first cell, PyCharm will start the Jupyter server and display the results inline. Once the server is started, dj-notebook [just works, as described in the usage guide](https://dj-notebook.readthedocs.io/en/latest/usage/). PyCharm's notebook interface [is documented here](https://www.jetbrains.com/help/pycharm/jupyter-notebook-support.html#ui). ![PyCharm - working notebook](img/pycharm/notebook_working.png) ================================================ FILE: docs/reference/index.md ================================================ # Reference - Code API Here's the reference or code API, the classes, functions, parameters, attributes, and all the dj-notebook parts. If you want to **learn dj-notebook** you are much better off reading the [usage docs](https://dj-notebook.readthedocs.io/en/latest/usage/). ================================================ FILE: docs/reference/plus.md ================================================ # `Plus` class Here's the reference for the `Plus` class, with all its parameters, attributes, and methods. ::: dj_notebook.shell_plus.Plus options: show_source: true members: - csv_to_df - diagram - mermaid - model_graph - model_graph_schema - print - read_frame ================================================ FILE: docs/releasing.md ================================================ # Releasing on PyPI 1. Update the `version` in `pyproject.toml` and `__version__` in` `src/__init__.py`. We use semantic versioning 2. Create a branch called `release-x.x.x` 3. At the command line, run `make tag` 4. Go to [tags page](https://github.com/pydanny/dj-notebook/tags), choose the most recent tag, and click `Draft a new release` 5. Click `Generate release notes` and then `Publish release notes` 6. Run `make changelog` 7. Use `git commit` and `git push` any files changed by this release 8. Send up with `git push origin release-x.x.x` 9. Merge to main ================================================ FILE: docs/usage.ipynb ================================================ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Usage\n", "\n", "All examples here are based on dj-notebook's test project at: \n", "\n", "[github.com/pydanny/dj-notebook/blob/main/tests/django_test_project](https://github.com/pydanny/dj-notebook/blob/main/tests/django_test_project)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "tags": [ "remove-input", "hide_code" ] }, "outputs": [], "source": [ "# Special configuration\n", "import pathlib\n", "import sys\n", "\n", "# project base\n", "here = pathlib.Path(\".\").parent\n", "PROJECT_ROOT = (here / \"..\" / \"tests\" / \"django_test_project\").resolve()\n", "sys.path.insert(0, str(PROJECT_ROOT))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Activation\n", "\n", "First, activate the project. If that doesn't work, try one of [the other methods](../activation) for activating dj-notebook." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n"
      ],
      "text/plain": []
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from dj_notebook import activate\n",
    "\n",
    "plus = activate(\"book_store.settings\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we can use the ORM:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       ", ]>"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from django.contrib.auth import get_user_model\n",
    "\n",
    "User = get_user_model()\n",
    "\n",
    "# Clean up the users\n",
    "User.objects.all().delete()\n",
    "\n",
    "# Create some users\n",
    "User.objects.create_user(\"Audrey\")\n",
    "User.objects.create_user(\"Daniel\")\n",
    "\n",
    "# Query the users\n",
    "User.objects.all()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Usage Plus\n",
    "\n",
    "When you activated the Django environment, you instantiated a variable called 'plus'. The 'plus' variable is an object that contains everything loaded from django-extensions' shell_plus. Here's a demonstration, let try running this snippet:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       ", ]>"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "plus.User.objects.all()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Or this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "admin | log entry | Can add log entry\n",
      "admin | log entry | Can change log entry\n",
      "admin | log entry | Can delete log entry\n",
      "admin | log entry | Can view log entry\n",
      "auth | group | Can add group\n"
     ]
    }
   ],
   "source": [
    "for perm in plus.Permission.objects.all()[:5]:\n",
    "    print(perm)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Dataframes from QuerySets\n",
    "\n",
    "_New in dj-notebook 0.3.0_\n",
    "\n",
    "Powered by [django-pandas](https://github.com/chrisdev/django-pandas), we can also trivially turn any Django QuerySet into a Dataframe."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
idpasswordlast_loginis_superuserusernamefirst_namelast_nameemailis_staffis_activedate_joined
030!e91xGexuejHJTtcK5UK6VLPs74uTojmlMVbBCHF1NoneFalseAudreyFalseTrue2023-10-21 12:54:07.318920+00:00
131!wqNcAZOEw4KUIQdaIzMyf46lgEYKbrLsGDHZgqtENoneFalseDanielFalseTrue2023-10-21 12:54:07.319889+00:00
\n", "
" ], "text/plain": [ " id password last_login is_superuser \\\n", "0 30 !e91xGexuejHJTtcK5UK6VLPs74uTojmlMVbBCHF1 None False \n", "1 31 !wqNcAZOEw4KUIQdaIzMyf46lgEYKbrLsGDHZgqtE None False \n", "\n", " username first_name last_name email is_staff is_active \\\n", "0 Audrey False True \n", "1 Daniel False True \n", "\n", " date_joined \n", "0 2023-10-21 12:54:07.318920+00:00 \n", "1 2023-10-21 12:54:07.319889+00:00 " ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "plus.read_frame(plus.User.objects.all())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Diagrams of Objects\n", "\n", "We're not done yet! \n", "\n", "We also provide a utility for introspection of classes, which can be useful in sophisticated project architectures. Let's see what happens when we use the `plus.diagram()` function:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "plus.diagram(plus.User)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Visualizing relations between models\n", "\n", "_New in dj-notebook 0.5.0_\n", "\n", "Useful for introspecting new or existing projects!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n"
      ],
      "text/plain": []
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [
       ""
      ],
      "text/plain": [
       ""
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "plus.model_graph(plus.User)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Rendering mermaid diagrams using dj-notebook\n",
    "\n",
    "_New in dj-notebook 0.4.0_\n",
    "\n",
    "Mermaid is such a useful tool tool that dj-notebook provides a shortcut."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       ""
      ],
      "text/plain": [
       ""
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "diagram = \"\"\"\n",
    "flowchart TD\n",
    "    A[pip install dj-notebook]\n",
    "    B[from dj_notebook import activate]\n",
    "    C[\"plus = activate()\"]\n",
    "    D[\"plus.mermaid(diagram)\"]\n",
    "    \n",
    "    A -->|wait a few seconds| B\n",
    "    B -.-> C\n",
    "    C -.-> D\n",
    "\"\"\"\n",
    "\n",
    "plus.mermaid(diagram)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Printing what dj-notebook loads from django-extensions\n",
    "\n",
    "_Vastly improved in dj-notebook 0.4.0_\n",
    "\n",
    "There are two ways to get a list of the loaded items by dj-notebook's `activate()` function:\n",
    "\n",
    "```python\n",
    "# Print all the objects to the screen on activate\n",
    "plus = activate(quiet_load=False)\n",
    "# Print the objects to the screen at any time\n",
    "plus.print()\n",
    "```\n",
    "\n",
    "Here is `plus.print()` in action:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "
# Shell Plus Model Imports                                                                                         \n",
       "from book_outlet.models import Address, Author, Book, Country                                                      \n",
       "from django.contrib.admin.models import LogEntry                                                                   \n",
       "from django.contrib.auth.models import Group, Permission, User                                                     \n",
       "from django.contrib.contenttypes.models import ContentType                                                         \n",
       "from django.contrib.sessions.models import Session                                                                 \n",
       "# Shell Plus Django Imports                                                                                        \n",
       "from django.core.cache import cache                                                                                \n",
       "from django.conf import settings                                                                                   \n",
       "from django.contrib.auth import get_user_model                                                                     \n",
       "from django.db import transaction                                                                                  \n",
       "from django.db.models import Avg, Case, Count, F, Max, Min, Prefetch, Q, Sum, When                                 \n",
       "from django.utils import timezone                                                                                  \n",
       "from django.urls import reverse                                                                                    \n",
       "from django.db.models import Exists, OuterRef, Subquery                                                            \n",
       "                                                                                                                   \n",
       "
\n" ], "text/plain": [ "\u001b[38;2;149;144;119;48;2;39;40;34m# Shell Plus Model Imports\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;255;70;137;48;2;39;40;34mfrom\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mbook_outlet\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mmodels\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;255;70;137;48;2;39;40;34mimport\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mAddress\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mAuthor\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mBook\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mCountry\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;255;70;137;48;2;39;40;34mfrom\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdjango\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mcontrib\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34madmin\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mmodels\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;255;70;137;48;2;39;40;34mimport\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mLogEntry\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;255;70;137;48;2;39;40;34mfrom\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdjango\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mcontrib\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mauth\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mmodels\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;255;70;137;48;2;39;40;34mimport\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mGroup\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mPermission\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mUser\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;255;70;137;48;2;39;40;34mfrom\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdjango\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mcontrib\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mcontenttypes\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mmodels\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;255;70;137;48;2;39;40;34mimport\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mContentType\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;255;70;137;48;2;39;40;34mfrom\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdjango\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mcontrib\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34msessions\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mmodels\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;255;70;137;48;2;39;40;34mimport\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mSession\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;149;144;119;48;2;39;40;34m# Shell Plus Django Imports\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;255;70;137;48;2;39;40;34mfrom\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdjango\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mcore\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mcache\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;255;70;137;48;2;39;40;34mimport\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mcache\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;255;70;137;48;2;39;40;34mfrom\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdjango\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mconf\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;255;70;137;48;2;39;40;34mimport\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34msettings\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;255;70;137;48;2;39;40;34mfrom\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdjango\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mcontrib\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mauth\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;255;70;137;48;2;39;40;34mimport\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mget_user_model\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;255;70;137;48;2;39;40;34mfrom\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdjango\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdb\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;255;70;137;48;2;39;40;34mimport\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mtransaction\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;255;70;137;48;2;39;40;34mfrom\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdjango\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdb\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mmodels\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;255;70;137;48;2;39;40;34mimport\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mAvg\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mCase\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mCount\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mF\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mMax\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mMin\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mPrefetch\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mQ\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mSum\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mWhen\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;255;70;137;48;2;39;40;34mfrom\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdjango\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mutils\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;255;70;137;48;2;39;40;34mimport\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mtimezone\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;255;70;137;48;2;39;40;34mfrom\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdjango\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34murls\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;255;70;137;48;2;39;40;34mimport\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mreverse\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;255;70;137;48;2;39;40;34mfrom\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdjango\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdb\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mmodels\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;255;70;137;48;2;39;40;34mimport\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mExists\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mOuterRef\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mSubquery\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[48;2;39;40;34m \u001b[0m\n" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "plus.print()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Dataframes from CSVs\n", "\n", "_New in dj-notebook 0.7.0_\n", "\n", "This turns strings or files on defined paths into Dataframes.\n", "\n" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
NameFirstLetter
0DanielD
1AudreyA
\n", "
" ], "text/plain": [ " Name FirstLetter\n", "0 Daniel D\n", "1 Audrey A" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "csv_string = \"\"\"Name,FirstLetter\n", "Daniel,D\n", "Audrey,A\"\"\"\n", "\n", "# Also works with plus.csv_to_df(pathlib.path('path/to/data.csv'))\n", "plus.csv_to_df(csv_string)" ] } ], "metadata": { "kernelspec": { "display_name": "dj-notebook", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.6" }, "orig_nbformat": 4 }, "nbformat": 4, "nbformat_minor": 2 } ================================================ FILE: mkdocs.yml ================================================ --- site_name: dj-notebook repo_url: https://github.com/pydanny/dj-notebook theme: name: material features: - navigation.instant - navigation.instant.prefetch - search.suggest - search.highlight - search.share logo: img/dj-notebook-logo.png icon: repo: fontawesome/brands/github markdown_extensions: - admonition - pymdownx.details - pymdownx.superfences plugins: - mkdocs-jupyter: remove_tag_config: remove_input_tags: [hide_code] - include-markdown: start: end: - search - social - mkdocstrings: handlers: python: options: extensions: [griffe_typingdoc] show_root_heading: true show_if_no_docstring: true inherited_members: true members_order: source separate_signature: true unwrap_annotated: true merge_init_into_class: true docstring_section_style: spacy signature_crossrefs: true show_symbol_type_heading: true show_symbol_type_toc: true nav: - Introduction: index.md - Installation: - Installation: installation.md - Using with PyCharm: pycharm.md - Activation: activation.md - Usage: usage.ipynb - Reference (Code API): [reference/index.md, reference/plus.md] - Contributing: contributing.md - Releasing: releasing.md - Changelog: changelog.md ================================================ FILE: pyproject.toml ================================================ [build-system] requires = ["setuptools>=61.0"] build-backend = "setuptools.build_meta" [project] name = "dj_notebook" version = "0.7.0" description = "Django + shell_plus + Jupyter notebooks made easy" readme = "README.md" authors = [ {name = "Daniel Roy Greenfeld", email = "daniel@feldroy.com"}, {name = "Anna Zhydko", email = "anna.zhydko@krakentechnologies.ltd"} ] maintainers = [ {name = "Daniel Roy Greenfeld", email = "daniel@feldroy.com"}, {name = "Anna Zhydko", email = "anna.zhydko@krakentechnologies.ltd"} ] classifiers = [ "Development Status :: 5 - Production/Stable", "Framework :: Django :: 4.0", "Framework :: Django :: 4.1", "Framework :: Django :: 4.2", "Framework :: Django :: 5.0", "Framework :: Jupyter", "License :: OSI Approved :: GNU General Public License (GPL)", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12" ] license = {text = "GNU General Public License v3"} dependencies = [ "django", "django-extensions", "django-pandas", "django-schema-graph", "ipython", "jupyter", "pandas", "rich", "python-dotenv" ] [project.optional-dependencies] dev = [ "black", # code auto-formatting "black[jupyter]", "coverage", # testing "griffe-typingdoc==0.2.2", "mkdocs-material", "mkdocs-jupyter", "mkdocs-material[imaging]", "mkdocs-include-markdown-plugin", "mkdocstrings[python]>=0.18", "mypy", # linting "pytest", # testing "ruff", # linting "yamlfix" # fixing the YAML ] [project.urls] bugs = "https://github.com/pydanny/dj-notebook/issues" changelog = "https://github.com/pydanny/dj-notebook/blob/master/CHANGELOG.md" homepage = "https://github.com/pydanny/dj-notebook" documentation = "https://dj-notebook.readthedocs.io/" [tool.setuptools] package-dir = {"" = "src"} # Mypy # ---- [tool.mypy] files = "." exclude = [ "tests/*" ] # Use strict defaults strict = true warn_unreachable = true warn_no_return = true [[tool.mypy.overrides]] # Don't require test functions to include types module = "tests.*" allow_untyped_defs = true disable_error_code = "attr-defined" # Ruff # ---- [tool.ruff] select = [ "E", # pycodestyle "F", # pyflakes "I", # isort ] ignore = [ "E501", # line too long - black takes care of this for us ] [tool.ruff.per-file-ignores] # Allow unused imports in __init__ files as these are convenience imports "**/__init__.py" = [ "F401" ] [tool.ruff.isort] lines-after-imports = 2 section-order = [ "future", "standard-library", "third-party", "first-party", "project", "local-folder", ] [tool.ruff.isort.sections] "project" = [ "src", "tests", ] ================================================ FILE: src/dj_notebook/__init__.py ================================================ import importlib import os import sys import warnings from pathlib import Path import django from django.conf import settings as django_settings from django.core.exceptions import ImproperlyConfigured from django.core.management.color import no_style from django_extensions.management import shells from IPython.utils.capture import capture_output from rich.status import Status from .config_helper import StrPath, find_django_settings_module from .shell_plus import Plus __version__ = "0.7.0" def activate( settings: str | None = None, quiet_load: bool = True, *, dotenv_file: StrPath | None = None, search_dir: StrPath | None = None, ) -> Plus: with Status( "Loading dj-notebook...\n Use Plus.print() to see what's been loaded.", spinner="bouncingBar", ): if settings: # If the caller specified a settings module explicitly, use that os.environ["DJANGO_SETTINGS_MODULE"] = settings else: source, discovered_settings = find_django_settings_module( dotenv_file=dotenv_file, search_dir=search_dir, ) if discovered_settings: if not quiet_load: print( f"Using {discovered_settings} as DJANGO_SETTINGS_MODULE, discovered from {source}" ) os.environ["DJANGO_SETTINGS_MODULE"] = discovered_settings try: _ = importlib.util.find_spec(discovered_settings) except ModuleNotFoundError: source_path = Path(source) if source.endswith("manage.py") and source_path.is_file(): source_dir = Path(source).parent.absolute() warnings.warn( f"{discovered_settings} from {source} could not be loaded. Adding {str(source_dir)} to search path." ) sys.path.append(str(source_dir)) else: raise ImproperlyConfigured( "DJANGO_SETTINGS_MODULE was not specified and could not be discovered." ) os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true" try: django.setup() except ModuleNotFoundError as e: raise ImproperlyConfigured( f"DJANGO_SETTINGS_MODULE {e.name} could not be loaded in django.setup()" ) with capture_output() as c: plus = Plus(shells.import_objects({"quiet_load": False}, no_style())) plus._import_object_history = c.stdout # Log a warning message when DEBUG is set to False if not plus.settings.DEBUG: warnings.warn("Django is running in production mode with dj-notebook.") if quiet_load is False: plus.print() return plus ================================================ FILE: src/dj_notebook/config_helper.py ================================================ import ast import os from pathlib import Path from typing import Generator, Tuple from dotenv import load_dotenv # taken from dotenv, which declares a similar type (but it doesn't look public...) # review note: the | syntax is new in python 3.10. If older pythons are generally being supported here, this should be # rewritten as Union[str, os.PathLike[str]] StrPath = str | os.PathLike[str] def setdefault_calls(module_path: Path) -> Generator[ast.Call, None, None]: """Yields all calls to `os.environ.setdefault` within a module.""" with open(module_path, "r") as module_src: parsed_module = ast.parse(module_src.read()) environ_id = None for node in ast.walk(parsed_module): if isinstance(node, ast.ImportFrom) and node.module == "os": for name in node.names: if isinstance(name, ast.alias) and name.name == "environ": environ_id = name.asname if name.asname is not None else name.name if ( isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr == "setdefault" ): if ( isinstance(node.func.value, ast.Attribute) and node.func.value.attr == "environ" ): if ( isinstance(node.func.value.value, ast.Name) and node.func.value.value.id == "os" ): yield node elif ( isinstance(node.func.value, ast.Name) and node.func.value.id == environ_id ): yield node def is_root(path: Path) -> bool: """ returns True if the supplied path is the root directory. This is only here because it seems clearer than `path.samefile(path.parent)` when reading a loop that walks up a directory hierarchy. """ return path.samefile(path.parent) # review note: the | syntax is new in python 3.10. If older pythons are generally being supported here, the type for # dotenv_file should be rewritten as Optional[StrPath] = None and the return type should be annotated as # Tuple[str, Optional[str]] def find_django_settings_module( *, dotenv_file: StrPath | None = None, search_dir: StrPath | None = None, ) -> Tuple[str, str | None]: """ Find the name of the first settings module from the environment or the closest `manage.py` file. Returns: a tuple(source, module name) telling the caller where the module was found and the name of the module. Optional keyword-only arguments: dotenv_file: Absolute or relative path to .env file, loaded prior to searching the environment. search_dir: Absolute or relative path to the directory to start searching for a `manage.py` file, used if `dotenv_file` is `None`. If both `dotenv_file` and `search_dir` are `None`, the environment variable DJANGO_SETTINGS_MODULE is checked, and the current working directory (and its parents and immediate subdirectories) is searched for a `manage.py` file. """ settings_module = None # First see if this has either already been set in the environment or put in a .env file that python-dotenv will # treat that way if dotenv_file: # load with override=True if the caller has specified a dotenv file explicitly source = "dotenv" load_dotenv(dotenv_file, override=bool(dotenv_file)) settings_module = os.environ.get("DJANGO_SETTINGS_MODULE", None) elif not search_dir: source = "environment" settings_module = os.environ.get("DJANGO_SETTINGS_MODULE", None) # If we get nothing from the environment, look for a `manage.py` script containing a call that sets a default in the # search directory, the current working directory, or any parent. This should accommodate the common pattern of # - app1 # - app2 # - project # --> settings.py # - scripts # - notebooks # --> analysis_notebook.ipynb # - manage.py current_search_dir = Path(search_dir or Path.cwd()).resolve() while settings_module is None: manage_py = current_search_dir / "manage.py" if manage_py.is_file(): for call in setdefault_calls(manage_py): if ( len(call.args) == 2 and call.args[0].value == "DJANGO_SETTINGS_MODULE" ): settings_module = call.args[1].value source = f"{manage_py.resolve().absolute()}" elif is_root(current_search_dir): break else: current_search_dir = current_search_dir.parent.resolve() if not settings_module: # Finally, go one level down into children of the search directory to see if a `manage.py` with a default # for `DJANGO_SETTINGS_MODULE` can be found there. This accommodates the common pattern of # - analysis.ipynb # - src # --> manage.py # --> project # ----> settings.py # ... for p in [ Path(subdir) for subdir in os.scandir(Path(search_dir or Path.cwd()).resolve()) ]: manage_py = p / "manage.py" if manage_py.is_file(): for call in setdefault_calls(manage_py): if ( len(call.args) == 2 and call.args[0].value == "DJANGO_SETTINGS_MODULE" ): settings_module = call.args[1].value source = manage_py.resolve().absolute() break return str(source), settings_module ================================================ FILE: src/dj_notebook/shell_plus.py ================================================ """ This module is intended to be imported at the beginning of a jupyter notebook to enable access to django objects with everything from django-extensions' shell_plus command and other utilities.: from dj_notebook import activate plus = activate As it accesses the database, it requires that: - The database is running in the background - The database connection variables are correctly configured """ import base64 import io import pathlib import typing import IPython import pandas as pd from django.db import models as django_models from django.db.models.query import QuerySet from django.utils.functional import cached_property from django_pandas.io import read_frame from IPython.display import display from rich.console import Console from rich.status import Status from rich.syntax import Syntax from schema_graph import schema console = Console() def display_mermaid(graph: str) -> None: """Renders the display with Mermaid.""" graphbytes = graph.encode("ascii") base64_bytes = base64.b64encode(graphbytes) base64_string = base64_bytes.decode("ascii") display(IPython.display.Image(url="https://mermaid.ink/img/" + base64_string)) class DiagramClass: """This class draws a class diagram for a given class and its ancestors.""" def __init__(self, base_class: type) -> None: self.base_class = base_class # To avoid duplicates the graph is a set self.graph = set() # Add the base_class to the graph self.graph.add( f' class {self.namify(self.base_class)}["{self.base_class.__module__}::{self.base_class.__name__}"]' # noqa: E501 ) # Draw connections between the base_class and its ancestors self.draw_connections(self.base_class) # Convert the set to a \n-seperated text file prefixed # with the classDiagram keyword from mermaidjs text = "classDiagram\n" + "\n".join(self.graph) # Use Mermaid to render the graph and Ipthon to display it display_mermaid(text) def draw_connections(self, class_: type) -> None: """Draw connections between a class and its ancestors, includes nodes and edges.""" for base in class_.__bases__: if base is not object: base_name = self.namify(base) self.graph.add( f' class {base_name}["{base.__module__}::{base.__name__}"]' ) connection = f" {base_name} <|-- {self.namify(class_)}" self.graph.add(connection) self.draw_connections(base) def namify(self, class_: object) -> str: """This provides a node name that keeps Mermaid happy.""" return f"{class_.__module__}_{class_.__name__}".replace(".", "_") class Plus: """Location of all the objects loaded by shell_plus and extra Jupyter-specific utilities.""" def __init__(self, helpers: dict[str, object]) -> None: self.helpers = helpers def __getattribute__(self, name: str) -> object: try: return object.__getattribute__(self, name) except AttributeError: helpers = object.__getattribute__(self, "helpers") if name in helpers: return helpers[name] else: raise def diagram(self, class_: object) -> None: """Draw a class diagram for a given class and its ancestors.""" if not isinstance(class_, type): class_ = type(class_) DiagramClass(class_) def print(self) -> None: """Print all the objects contained by the Plus object.""" console.print(Syntax(self._import_object_history, "python")) def read_frame(self, qs: QuerySet) -> pd.DataFrame: """Converts a Django QuerySet into a Pandas DataFrame.""" return read_frame(qs) def mermaid(self, diagram: str) -> None: """Render a mermaid diagram.""" display_mermaid(diagram) @cached_property def model_graph_schema(self) -> dict[typing.Any, typing.Any]: """Cached property for the graph data.""" with Status( "Converting the models into a schema graph...", spinner="bouncingBar", ): graph = schema.get_schema() return graph def model_graph(self, model: django_models.Model, max_nodes: int = 20) -> None: """Draw a diagram of the specified model in the database.""" edges = get_edges_for_model(self.model_graph_schema, model) if len(edges) > max_nodes: console.print( f"[red bold]Warning: Model {model} has more than {max_nodes} nodes. " "The diagram may be too large to render." ) output = """flowchart TD\n""" for edge in edges: output += ( f" {edge.source.split('.')[-1]} --- {edge.target.split('.')[-1]}\n" ) display_mermaid(output) def csv_to_df(self, filepath_or_string: pathlib.Path | str) -> pd.DataFrame: """Read a CSV file into a Pandas DataFrame.""" # Process as a Path object if isinstance(filepath_or_string, pathlib.Path): return pd.read_csv(filepath_or_string) # Process as a string, which we convert to a filebuffer buffer = io.StringIO(filepath_or_string) return pd.read_csv(buffer) def get_node_for_model(graph, model: django_models.Model): try: return next( filter(lambda x: x.id == schema.get_model_id(model), graph.nodes), None ) except StopIteration: raise Exception("Model not found in graph") def get_edges_for_model(graph, model: django_models.Model): node = get_node_for_model(graph, model) return list( filter(lambda x: x.source == node.id or x.target == node.id, graph.edges) ) ================================================ FILE: tests/__init__.py ================================================ ================================================ FILE: tests/config_debug_false.py ================================================ # This very incomplete configuration allows unit tests to take the same path as a standard call # to activate(). This one enables the test for a warning when DEBUG == False to pass. INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", ] USE_TZ = True DEBUG = False ================================================ FILE: tests/config_test_harness.py ================================================ # This very incomplete configuration allows unit tests to take the same path as a standard call # to activate() INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", ] USE_TZ = True DEBUG = True ================================================ FILE: tests/django_test_project/book_outlet/__init__.py ================================================ ================================================ FILE: tests/django_test_project/book_outlet/admin.py ================================================ from django.contrib import admin from .models import Address, Author, Book, Country # Register your models here. class BookAdmin(admin.ModelAdmin): prepopulated_fields = {"slug": ("title",)} list_filter = ( "title", "rating", ) list_display = ( "title", "author", ) admin.site.register(Book, BookAdmin) admin.site.register(Author) admin.site.register(Address) admin.site.register(Country) ================================================ FILE: tests/django_test_project/book_outlet/apps.py ================================================ from django.apps import AppConfig class BookOutletConfig(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "book_outlet" ================================================ FILE: tests/django_test_project/book_outlet/migrations/0001_initial.py ================================================ # Generated by Django 4.2.2 on 2023-06-14 11:14 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name="Book", fields=[ ( "id", models.BigAutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("title", models.CharField(max_length=50)), ("rating", models.IntegerField()), ], ), ] ================================================ FILE: tests/django_test_project/book_outlet/migrations/0002_book_author_book_is_bestselling_alter_book_rating.py ================================================ # Generated by Django 4.2.2 on 2023-06-14 16:20 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("book_outlet", "0001_initial"), ] operations = [ migrations.AddField( model_name="book", name="author", field=models.CharField(max_length=100, null=True), ), migrations.AddField( model_name="book", name="is_bestselling", field=models.BooleanField(default=False), ), migrations.AlterField( model_name="book", name="rating", field=models.IntegerField( validators=[ django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(5), ] ), ), ] ================================================ FILE: tests/django_test_project/book_outlet/migrations/0003_book_slug.py ================================================ # Generated by Django 4.2.2 on 2023-06-28 10:50 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("book_outlet", "0002_book_author_book_is_bestselling_alter_book_rating"), ] operations = [ migrations.AddField( model_name="book", name="slug", field=models.SlugField(default=""), ), ] ================================================ FILE: tests/django_test_project/book_outlet/migrations/0004_author_alter_book_slug_alter_book_author.py ================================================ # Generated by Django 4.2.2 on 2023-07-05 11:09 import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("book_outlet", "0003_book_slug"), ] operations = [ migrations.CreateModel( name="Author", fields=[ ( "id", models.BigAutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("first_name", models.CharField(max_length=100)), ("last_name", models.CharField(max_length=100)), ], ), migrations.AlterField( model_name="book", name="slug", field=models.SlugField(blank=True, default=""), ), migrations.AlterField( model_name="book", name="author", field=models.ForeignKey( null=True, on_delete=django.db.models.deletion.CASCADE, to="book_outlet.author", ), ), ] ================================================ FILE: tests/django_test_project/book_outlet/migrations/0005_alter_book_author.py ================================================ # Generated by Django 4.2.2 on 2023-07-05 11:33 import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("book_outlet", "0004_author_alter_book_slug_alter_book_author"), ] operations = [ migrations.AlterField( model_name="book", name="author", field=models.ForeignKey( null=True, on_delete=django.db.models.deletion.CASCADE, related_name="books", to="book_outlet.author", ), ), ] ================================================ FILE: tests/django_test_project/book_outlet/migrations/0006_address_author_address.py ================================================ # Generated by Django 4.2.2 on 2023-07-12 11:12 import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("book_outlet", "0005_alter_book_author"), ] operations = [ migrations.CreateModel( name="Address", fields=[ ( "id", models.BigAutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("street", models.CharField(max_length=80)), ("postal_code", models.CharField(max_length=5)), ("city", models.CharField(max_length=50)), ], ), migrations.AddField( model_name="author", name="address", field=models.OneToOneField( null=True, on_delete=django.db.models.deletion.CASCADE, to="book_outlet.address", ), ), ] ================================================ FILE: tests/django_test_project/book_outlet/migrations/0007_country_alter_address_options_and_more.py ================================================ # Generated by Django 4.2.2 on 2023-07-14 09:35 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("book_outlet", "0006_address_author_address"), ] operations = [ migrations.CreateModel( name="Country", fields=[ ( "id", models.BigAutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("name", models.CharField(max_length=80)), ("code", models.CharField(max_length=2)), ], ), migrations.AlterModelOptions( name="address", options={"verbose_name_plural": "Address Entries"}, ), migrations.AddField( model_name="book", name="published_countries", field=models.ManyToManyField(to="book_outlet.country"), ), ] ================================================ FILE: tests/django_test_project/book_outlet/migrations/__init__.py ================================================ ================================================ FILE: tests/django_test_project/book_outlet/models.py ================================================ from django.core.validators import MaxValueValidator, MinValueValidator from django.db import models from django.urls import reverse from django.utils.text import slugify class Country(models.Model): name = models.CharField(max_length=80) code = models.CharField(max_length=2) def __str__(self): return f"{self.name}, {self.code}" class Meta: verbose_name_plural = "Countries" class Address(models.Model): street = models.CharField(max_length=80) postal_code = models.CharField(max_length=5) city = models.CharField(max_length=50) def __str__(self): return f"{self.street}, {self.postal_code}, {self.city}" class Meta: verbose_name_plural = "Address Entries" class Author(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) address = models.OneToOneField(Address, on_delete=models.CASCADE, null=True) def full_name(self): return f"{self.first_name} {self.last_name}" def __str__(self): return self.full_name() class Book(models.Model): title = models.CharField(max_length=50) rating = models.IntegerField( validators=[MinValueValidator(1), MaxValueValidator(5)] ) author = models.ForeignKey( Author, on_delete=models.CASCADE, null=True, related_name="books" ) is_bestselling = models.BooleanField(default=False) slug = models.SlugField(default="", blank=True, null=False, db_index=True) published_countries = models.ManyToManyField(Country) def get_absolute_url(self): return reverse("book-detail", args=[self.slug]) def save(self, *args, **kwargs): self.slug = slugify(self.title) super().save(*args, **kwargs) def __str__(self): return f"{self.title} ({self.rating})" ================================================ FILE: tests/django_test_project/book_outlet/templates/book_outlet/base.html ================================================ {% block title %}{% endblock %} {% block content %} {% endblock %} ================================================ FILE: tests/django_test_project/book_outlet/templates/book_outlet/book_detail.html ================================================ {% extends "book_outlet/base.html" %} {% block title %} {{ title }} {% endblock %} {% block content %}

{{ title }}

{{ author }}

The book has a rating of {{ rating }} {% if is_bestseller %} and is a bestseller. {% else %} but isn't a bestseller. {% endif %}

{% endblock %} ================================================ FILE: tests/django_test_project/book_outlet/templates/book_outlet/index.html ================================================ {% extends "book_outlet/base.html" %} {% block title %} All books {% endblock %} {% block content %}

Total Nuber of Books: {{ total_number_of_books }}

Average Rating: {{ average_rating.rating__avg }}

{% endblock %} ================================================ FILE: tests/django_test_project/book_outlet/tests.py ================================================ # Create your tests here. ================================================ FILE: tests/django_test_project/book_outlet/urls.py ================================================ from django.urls import path from . import views urlpatterns = [ path("", views.index), path("", views.book_detail, name="book-detail"), ] ================================================ FILE: tests/django_test_project/book_outlet/views.py ================================================ from django.db.models import Avg from django.http import Http404 from django.shortcuts import get_object_or_404, render from .models import Book # Create your views here. def index(request): books = Book.objects.all().order_by("-title") num_books = books.count() avg_rating = books.aggregate(Avg("rating")) return render( request, "book_outlet/index.html", { "books": books, "total_number_of_books": num_books, "average_rating": avg_rating, }, ) def book_detail(request, slug): try: book = Book.objects.get(slug=slug) except Book.DoesNotExist: raise Http404() book = get_object_or_404(Book, slug=slug) return render( request, "book_outlet/book_detail.html", { "title": book.title, "author": book.author, "rating": book.rating, "is_bestseller": book.is_bestselling, }, ) ================================================ FILE: tests/django_test_project/book_store/__init__.py ================================================ ================================================ FILE: tests/django_test_project/book_store/asgi.py ================================================ """ ASGI config for book_store project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/4.1/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "book_store.settings") application = get_asgi_application() ================================================ FILE: tests/django_test_project/book_store/settings.py ================================================ """ Django settings for book_store project. Generated by 'django-admin startproject' using Django 4.1.7. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.1/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = "django-insecure-4_!#@9yicst-z-*7mtf026@qp0+modu41si78gg88h_f12n(y1" # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ "book_outlet", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] ROOT_URLCONF = "book_store.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "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", ], }, }, ] WSGI_APPLICATION = "book_store.wsgi.application" # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": BASE_DIR / "data.sqlite3", } } # Password validation # https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { "NAME": "django.contrib.auth.password_validation." "UserAttributeSimilarityValidator", }, { "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", }, { "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator", }, { "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator", }, ] # Internationalization # https://docs.djangoproject.com/en/4.1/topics/i18n/ LANGUAGE_CODE = "en-us" TIME_ZONE = "UTC" USE_I18N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.1/howto/static-files/ STATIC_URL = "static/" # Default primary key field type # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" ================================================ FILE: tests/django_test_project/book_store/urls.py ================================================ """book_store URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import include, path urlpatterns = [path("admin/", admin.site.urls), path("", include("book_outlet.urls"))] ================================================ FILE: tests/django_test_project/book_store/wsgi.py ================================================ """ WSGI config for book_store project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/4.1/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "book_store.settings") application = get_wsgi_application() ================================================ FILE: tests/django_test_project/example_fk.ipynb ================================================ { "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "a6a7088ce9fc45e3bb46a3c6dbf1f2cf", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Output()" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
\n"
      ],
      "text/plain": []
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from dj_notebook import activate\n",
    "\n",
    "\n",
    "plus = activate(\"book_store.settings\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "
\n"
      ],
      "text/plain": []
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [
       ""
      ],
      "text/plain": [
       ""
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from rich import print\n",
    "\n",
    "# print(plus.graph_data)\n",
    "plus.model_graph(plus.Book)\n",
    "# for model, relations in plus.graph_data.items():\n",
    "#     print(model, [x for x in relations])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       ""
      ],
      "text/plain": [
       ""
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "plus.model_graph(plus.Country)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       ""
      ],
      "text/plain": [
       ""
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "plus.model_graph(plus.User)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "dj-notebook",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.6"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}


================================================
FILE: tests/django_test_project/example_long_form.ipynb
================================================
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import django\n",
    "import os\n",
    "\n",
    "os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"book_store.settings\")\n",
    "os.environ[\"DJANGO_ALLOW_ASYNC_UNSAFE\"] = \"true\"\n",
    "django.setup()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       ""
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from book_outlet.models import Book\n",
    "\n",
    "Book.objects.all()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "dj-notebook",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.6"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}


================================================
FILE: tests/django_test_project/example_mermaid.ipynb
================================================
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "
\n"
      ],
      "text/plain": []
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from dj_notebook import activate\n",
    "\n",
    "plus = activate(\"book_store.settings\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       ""
      ],
      "text/plain": [
       ""
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "diagram = \"\"\"\n",
    "flowchart TD\n",
    "    B(from dj_notebook import activate)\n",
    "    C[\"plus = activate()\"]\n",
    "    D(\"plus.mermaid(diagram)\")\n",
    "    A[pip install dj-notebook] -->|wait a few seconds| B\n",
    "    B -.-> C\n",
    "    C -.-> D\n",
    "\"\"\"\n",
    "\n",
    "plus.mermaid(diagram)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "dj-notebook",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.6"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}


================================================
FILE: tests/django_test_project/example_print.ipynb
================================================
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "eb7342be620e4f32a22efe83e24b19b0",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Output()"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [
       "
# Shell Plus Model Imports                                                                                         \n",
       "from book_outlet.models import Address, Author, Book, Country                                                      \n",
       "from django.contrib.admin.models import LogEntry                                                                   \n",
       "from django.contrib.auth.models import Group, Permission, User                                                     \n",
       "from django.contrib.contenttypes.models import ContentType                                                         \n",
       "from django.contrib.sessions.models import Session                                                                 \n",
       "# Shell Plus Django Imports                                                                                        \n",
       "from django.core.cache import cache                                                                                \n",
       "from django.conf import settings                                                                                   \n",
       "from django.contrib.auth import get_user_model                                                                     \n",
       "from django.db import transaction                                                                                  \n",
       "from django.db.models import Avg, Case, Count, F, Max, Min, Prefetch, Q, Sum, When                                 \n",
       "from django.utils import timezone                                                                                  \n",
       "from django.urls import reverse                                                                                    \n",
       "from django.db.models import Exists, OuterRef, Subquery                                                            \n",
       "                                                                                                                   \n",
       "
\n" ], "text/plain": [ "\u001b[38;2;149;144;119;48;2;39;40;34m# Shell Plus Model Imports\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;255;70;137;48;2;39;40;34mfrom\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mbook_outlet\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mmodels\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;255;70;137;48;2;39;40;34mimport\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mAddress\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mAuthor\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mBook\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mCountry\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;255;70;137;48;2;39;40;34mfrom\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdjango\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mcontrib\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34madmin\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mmodels\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;255;70;137;48;2;39;40;34mimport\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mLogEntry\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;255;70;137;48;2;39;40;34mfrom\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdjango\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mcontrib\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mauth\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mmodels\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;255;70;137;48;2;39;40;34mimport\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mGroup\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mPermission\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mUser\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;255;70;137;48;2;39;40;34mfrom\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdjango\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mcontrib\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mcontenttypes\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mmodels\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;255;70;137;48;2;39;40;34mimport\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mContentType\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;255;70;137;48;2;39;40;34mfrom\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdjango\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mcontrib\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34msessions\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mmodels\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;255;70;137;48;2;39;40;34mimport\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mSession\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;149;144;119;48;2;39;40;34m# Shell Plus Django Imports\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;255;70;137;48;2;39;40;34mfrom\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdjango\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mcore\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mcache\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;255;70;137;48;2;39;40;34mimport\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mcache\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;255;70;137;48;2;39;40;34mfrom\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdjango\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mconf\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;255;70;137;48;2;39;40;34mimport\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34msettings\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;255;70;137;48;2;39;40;34mfrom\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdjango\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mcontrib\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mauth\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;255;70;137;48;2;39;40;34mimport\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mget_user_model\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;255;70;137;48;2;39;40;34mfrom\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdjango\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdb\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;255;70;137;48;2;39;40;34mimport\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mtransaction\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;255;70;137;48;2;39;40;34mfrom\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdjango\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdb\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mmodels\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;255;70;137;48;2;39;40;34mimport\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mAvg\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mCase\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mCount\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mF\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mMax\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mMin\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mPrefetch\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mQ\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mSum\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mWhen\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;255;70;137;48;2;39;40;34mfrom\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdjango\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mutils\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;255;70;137;48;2;39;40;34mimport\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mtimezone\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;255;70;137;48;2;39;40;34mfrom\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdjango\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34murls\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;255;70;137;48;2;39;40;34mimport\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mreverse\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;255;70;137;48;2;39;40;34mfrom\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdjango\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdb\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mmodels\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;255;70;137;48;2;39;40;34mimport\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mExists\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mOuterRef\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mSubquery\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[48;2;39;40;34m \u001b[0m\n" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
\n"
      ],
      "text/plain": []
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from dj_notebook import activate\n",
    "\n",
    "plus = activate(\"book_store.settings\", quiet_load=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       ", ]>"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "plus.User.objects.all()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "
# Shell Plus Model Imports                                                                                         \n",
       "from book_outlet.models import Address, Author, Book, Country                                                      \n",
       "from django.contrib.admin.models import LogEntry                                                                   \n",
       "from django.contrib.auth.models import Group, Permission, User                                                     \n",
       "from django.contrib.contenttypes.models import ContentType                                                         \n",
       "from django.contrib.sessions.models import Session                                                                 \n",
       "# Shell Plus Django Imports                                                                                        \n",
       "from django.core.cache import cache                                                                                \n",
       "from django.conf import settings                                                                                   \n",
       "from django.contrib.auth import get_user_model                                                                     \n",
       "from django.db import transaction                                                                                  \n",
       "from django.db.models import Avg, Case, Count, F, Max, Min, Prefetch, Q, Sum, When                                 \n",
       "from django.utils import timezone                                                                                  \n",
       "from django.urls import reverse                                                                                    \n",
       "from django.db.models import Exists, OuterRef, Subquery                                                            \n",
       "                                                                                                                   \n",
       "
\n" ], "text/plain": [ "\u001b[38;2;149;144;119;48;2;39;40;34m# Shell Plus Model Imports\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;255;70;137;48;2;39;40;34mfrom\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mbook_outlet\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mmodels\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;255;70;137;48;2;39;40;34mimport\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mAddress\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mAuthor\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mBook\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mCountry\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;255;70;137;48;2;39;40;34mfrom\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdjango\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mcontrib\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34madmin\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mmodels\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;255;70;137;48;2;39;40;34mimport\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mLogEntry\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;255;70;137;48;2;39;40;34mfrom\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdjango\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mcontrib\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mauth\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mmodels\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;255;70;137;48;2;39;40;34mimport\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mGroup\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mPermission\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mUser\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;255;70;137;48;2;39;40;34mfrom\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdjango\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mcontrib\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mcontenttypes\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mmodels\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;255;70;137;48;2;39;40;34mimport\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mContentType\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;255;70;137;48;2;39;40;34mfrom\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdjango\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mcontrib\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34msessions\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mmodels\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;255;70;137;48;2;39;40;34mimport\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mSession\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;149;144;119;48;2;39;40;34m# Shell Plus Django Imports\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;255;70;137;48;2;39;40;34mfrom\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdjango\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mcore\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mcache\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;255;70;137;48;2;39;40;34mimport\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mcache\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;255;70;137;48;2;39;40;34mfrom\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdjango\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mconf\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;255;70;137;48;2;39;40;34mimport\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34msettings\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;255;70;137;48;2;39;40;34mfrom\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdjango\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mcontrib\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mauth\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;255;70;137;48;2;39;40;34mimport\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mget_user_model\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;255;70;137;48;2;39;40;34mfrom\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdjango\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdb\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;255;70;137;48;2;39;40;34mimport\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mtransaction\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;255;70;137;48;2;39;40;34mfrom\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdjango\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdb\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mmodels\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;255;70;137;48;2;39;40;34mimport\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mAvg\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mCase\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mCount\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mF\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mMax\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mMin\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mPrefetch\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mQ\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mSum\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mWhen\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;255;70;137;48;2;39;40;34mfrom\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdjango\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mutils\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;255;70;137;48;2;39;40;34mimport\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mtimezone\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;255;70;137;48;2;39;40;34mfrom\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdjango\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34murls\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;255;70;137;48;2;39;40;34mimport\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mreverse\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[38;2;255;70;137;48;2;39;40;34mfrom\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdjango\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mdb\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m.\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mmodels\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;255;70;137;48;2;39;40;34mimport\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mExists\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mOuterRef\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m,\u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mSubquery\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\n", "\u001b[48;2;39;40;34m \u001b[0m\n" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "plus.print()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "dj-notebook", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.6" }, "orig_nbformat": 4 }, "nbformat": 4, "nbformat_minor": 2 } ================================================ FILE: tests/django_test_project/example_short_form.ipynb ================================================ { "cells": [ { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "from dj_notebook import activate\n", "\n", "plus = activate(\"book_store.settings\")" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "plus.User.objects.all()" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from django.contrib.auth import get_user_model\n", "\n", "User = get_user_model()\n", "User.objects.all()" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "plus.diagram(plus.User)" ] } ], "metadata": { "kernelspec": { "display_name": "dj-notebook", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.6" }, "orig_nbformat": 4 }, "nbformat": 4, "nbformat_minor": 2 } ================================================ FILE: tests/django_test_project/manage.py ================================================ #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "book_store.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == "__main__": main() ================================================ FILE: tests/env.django_settings_module ================================================ DJANGO_SETTINGS_MODULE=bip.config ================================================ FILE: tests/fake_manage_alias_environ.py ================================================ from os import environ as os_environ if __name__ == "__main__": os_environ.setdefault("DJANGO_SETTINGS_MODULE", "baz.settings") ================================================ FILE: tests/fake_manage_fully_qualified.py ================================================ import os if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "foo.settings") ================================================ FILE: tests/fake_manage_import_environ.py ================================================ from os import environ if __name__ == "__main__": environ.setdefault("DJANGO_SETTINGS_MODULE", "bar.settings") ================================================ FILE: tests/fake_other_environ_and_real_environ_setdefault.py ================================================ import os class Environ: def setdefault(self, k: str, v: str) -> None: print(f"{k}={v}") environ = Environ() if __name__ == "__main__": environ.setdefault("DJANGO_SETTINGS_MODULE", "foo.bar.settings") os.environ.setdefault("DJANGO_SETTINGS_MODULE", "foo.bar.os.environ.settings") ================================================ FILE: tests/fake_other_environ_setdefault.py ================================================ class Environ: def setdefault(self, k: str, v: str) -> None: print(f"{k}={v}") environ = Environ() if __name__ == "__main__": environ.setdefault("DJANGO_SETTINGS_MODULE", "foo.bar.settings") ================================================ FILE: tests/sample.csv ================================================ Name,Age,Weight A,1,100 B,2,200 ================================================ FILE: tests/test_config_helper.py ================================================ import os from pathlib import Path from dj_notebook.config_helper import find_django_settings_module, setdefault_calls class EnvironmentGuard: def __enter__(self): self.original_environment = {} for k in os.environ.keys(): self.original_environment[k] = os.environ[k] return None def __exit__(self, exc_type, exc_val, exc_tb): for k in os.environ.keys(): del os.environ[k] for k in self.original_environment.keys(): os.environ[k] = self.original_environment[k] def test_setdefault_calls_fully_qualified(): script_dir_path = Path(os.path.dirname(os.path.realpath(__file__))) manage_py = script_dir_path / "fake_manage_fully_qualified.py" calls = list(setdefault_calls(manage_py)) assert len(calls) == 1 assert calls[0].args[0].value == "DJANGO_SETTINGS_MODULE" assert calls[0].args[1].value == "foo.settings" def test_setdefault_calls_import_function(): script_dir_path = Path(os.path.dirname(os.path.realpath(__file__))) manage_py = script_dir_path / "fake_manage_import_environ.py" calls = list(setdefault_calls(manage_py)) assert len(calls) == 1 assert calls[0].args[0].value == "DJANGO_SETTINGS_MODULE" assert calls[0].args[1].value == "bar.settings" def test_setdefault_calls_import_alias(): script_dir_path = Path(os.path.dirname(os.path.realpath(__file__))) manage_py = script_dir_path / "fake_manage_alias_environ.py" calls = list(setdefault_calls(manage_py)) assert len(calls) == 1 assert calls[0].args[0].value == "DJANGO_SETTINGS_MODULE" assert calls[0].args[1].value == "baz.settings" def test_setdefault_calls_skips_wrong_function(): script_dir_path = Path(os.path.dirname(os.path.realpath(__file__))) manage_py = script_dir_path / "fake_other_environ_setdefault.py" calls = list(setdefault_calls(manage_py)) assert len(calls) == 0 def test_setdefault_calls_skips_wrong_function_finds_right_function(): script_dir_path = Path(os.path.dirname(os.path.realpath(__file__))) manage_py = script_dir_path / "fake_other_environ_and_real_environ_setdefault.py" calls = list(setdefault_calls(manage_py)) assert len(calls) == 1 assert calls[0].args[0].value == "DJANGO_SETTINGS_MODULE" assert calls[0].args[1].value == "foo.bar.os.environ.settings" def test_find_django_settings_module_dotenv(): script_dir_path = Path(os.path.dirname(os.path.realpath(__file__))) env_file = script_dir_path / "env.django_settings_module" with EnvironmentGuard(): source, found = find_django_settings_module(dotenv_file=env_file) assert source == "dotenv" assert os.environ["DJANGO_SETTINGS_MODULE"] == found assert found == "bip.config" def test_find_django_settings_module_dotenv_overrides(): script_dir_path = Path(os.path.dirname(os.path.realpath(__file__))) env_file = script_dir_path / "env.django_settings_module" with EnvironmentGuard(): os.environ["DJANGO_SETTINGS_MODULE"] = "something.else" source, found = find_django_settings_module(dotenv_file=env_file) assert source == "dotenv" assert os.environ["DJANGO_SETTINGS_MODULE"] == found assert found == "bip.config" def test_find_django_settings_module_os_environment(): with EnvironmentGuard(): os.environ["DJANGO_SETTINGS_MODULE"] = "something.else" source, found = find_django_settings_module() assert source == "environment" assert os.environ["DJANGO_SETTINGS_MODULE"] == found assert found == "something.else" def test_find_django_settings_module_remote_path(): script_dir_path = Path(os.path.dirname(os.path.realpath(__file__))) django_project_path = script_dir_path / "django_test_project" old_cwd = os.getcwd() # Change to a directory that is not the django project or adjacent. os.chdir(script_dir_path / "..") with EnvironmentGuard(): source, found = find_django_settings_module(search_dir=django_project_path) assert source == str(django_project_path / "manage.py") assert found == "book_store.settings" # Change to the parent directory in order to search children source, found = None, None with EnvironmentGuard(): source, found = find_django_settings_module( search_dir=django_project_path / ".." ) assert source == str(django_project_path / "manage.py") assert found == "book_store.settings" # Change to a child directory in order to search parents source, found = None, None with EnvironmentGuard(): source, found = find_django_settings_module( search_dir=django_project_path / "book_store" ) assert source == str(django_project_path / "manage.py") assert found == "book_store.settings" os.chdir(old_cwd) ================================================ FILE: tests/test_dj_notebook.py ================================================ import os from os import environ from pathlib import Path from unittest.mock import patch import django.conf import pandas import pytest from dj_notebook import Plus, activate from dj_notebook.shell_plus import DiagramClass from django import conf as django_conf from django.core.exceptions import ImproperlyConfigured from dotenv import load_dotenv class SettingsCleaner: """ A context manager that saves and restores the value of `DJANGO_SETTINGS_MODULE` along with resetting `djang.conf.settings` on both enter and exit, to prevent tests that rely on different django settings from accidentally depending on each other. """ def __enter__(self): self.old_settings_env = environ.get("DJANGO_SETTINGS_MODULE", None) if self.old_settings_env is not None: del environ["DJANGO_SETTINGS_MODULE"] django_conf.settings = django.conf.LazySettings() return None def __exit__(self, exc_type, exc_val, exc_tb): if self.old_settings_env is not None: environ["DJANGO_SETTINGS_MODULE"] = self.old_settings_env elif "DJANGO_SETTINGS_MODULE" in environ: del environ["DJANGO_SETTINGS_MODULE"] django.conf.settings = django.conf.LazySettings() def test_thing(): with SettingsCleaner(): plus = activate("tests.config_test_harness") # TODO capture STDOUT and assert on it assert plus.print() is None def test_namify(): """ Test the `namify` method of the `DiagramClass`. Checks if the `namify` method correctly converts the class name and its module into a format that replaces dots with underscores. Test covers three scenarios: 1. Built-in classes (e.g., `str`). 2. Custom classes (e.g., `DiagramClass`). 3. Nested classes (e.g., `OuterClass.InnerClass`). TODO: Maybe add scenarios of periods included in naming to test conversion """ # Create an instance of DiagramClass - include a sample class diagram = DiagramClass(str) # Test built-in class assert diagram.namify(str) == "builtins_str" # Test custom class assert diagram.namify(DiagramClass) == "dj_notebook_shell_plus_DiagramClass" # Test nested class class OuterClass: class InnerClass: pass assert diagram.namify(OuterClass.InnerClass) == "tests_test_dj_notebook_InnerClass" def test_draw_connections(): """ Test the `draw_connections` functionality of the `DiagramClass`. Verifies that the graph generated by `DiagramClass` correctly reflects the relationships between a sample class (`SampleClass`) and its direct base classes (`TestClassA` and `TestClassB`). TODO: There is an oddity with needing to add 2 leading spaces to the assertions... look on line 47 in the `draw_connections` definition which it needs to match. """ # Define base classes class TestClassA: pass class TestClassB: pass # Create a sample class that inherits from the base classes class SampleClass(TestClassA, TestClassB): pass diagram = DiagramClass(SampleClass) # Check if the graph has nodes for the SampleClass and its ancestors sample_class_node = ( f" class {diagram.namify(SampleClass)}" f'["{SampleClass.__module__}::{SampleClass.__name__}"]' ) assert sample_class_node in diagram.graph test_class_a_node = ( f" class {diagram.namify(TestClassA)}" f'["{TestClassA.__module__}::{TestClassA.__name__}"]' ) assert test_class_a_node in diagram.graph test_class_b_node = ( f" class {diagram.namify(TestClassB)}" f'["{TestClassB.__module__}::{TestClassB.__name__}"]' ) assert test_class_b_node in diagram.graph # Check if the graph has connections between the SampleClass and its ancestors assert ( f" {diagram.namify(TestClassA)} <|-- {diagram.namify(SampleClass)}" in diagram.graph ) assert ( f" {diagram.namify(TestClassB)} <|-- {diagram.namify(SampleClass)}" in diagram.graph ) # Create a mock for QuerySet. class MockQuerySet: pass @pytest.fixture def mock_read_frame(): # Mock the external read_frame function from django_pandas.io # since this proj uses a wrapper around it - test directly with patch("django_pandas.io.read_frame") as mock_rf: mock_rf.return_value = "Mocked DataFrame" yield mock_rf def test_read_frame(mock_read_frame): """ Tests the `read_frame` method of the `Plus` class to ensure it properly delegates to the `django_pandas.io` wrapper around pandas, using a provided QuerySet. The test mocks this function to return "Mocked DataFrame" and checks if the `Plus` method returns this when given a mock QuerySet. """ plus_instance = Plus(helpers={}) mock_qs = MockQuerySet() # Bypass __getattribute__ and directly set the read_frame method to the mock plus_instance.read_frame = mock_read_frame result = plus_instance.read_frame(mock_qs) # assert mocked query called mock_read_frame.assert_called_once_with(mock_qs) assert result == "Mocked DataFrame" def test_csv_to_df(): """ Tests the `csv_to_df` method of the `Plus` class to ensure it returns a CSV. The test mocks this function to return "Mocked DataFrame" and checks if the `Plus` method returns this when given a mock CSV. """ plus_instance = Plus(helpers={}) csv_path = Path("tests/sample.csv") with open(csv_path) as f: csv_string = f.read() result_from_string = plus_instance.csv_to_df(csv_string) result_from_path = plus_instance.csv_to_df(csv_path) # assert results are dataframes assert isinstance(result_from_string, pandas.DataFrame) assert isinstance(result_from_path, pandas.DataFrame) # assert content is correct assert result_from_string.at[0, "Name"] == "A" assert result_from_path.at[0, "Name"] == "A" def test_warning_when_debug_false(capfd): """ Test if the correct warning and message are displayed when DEBUG is False. Checks for error string message in both stout and warnings. Test assumes that calling activate("fake_settings") results in a state where DEBUG is False. Args: capfd: Pytest fixture to capture stdout and stderr. """ with SettingsCleaner(): with pytest.warns(UserWarning) as record: activate("tests.config_debug_false") # Capture STDOUT and STDERR capfd.readouterr() # Check warning message assert "Django is running in production mode with dj-notebook." in [ str(r.message) for r in record.list ] def test_settings_discovery_subdirectory(): # when run from the makefile, this gets its cwd set to the project root. for discovery to work as intended, the cwd # needs to be tests old_cwd = os.getcwd() os.chdir(os.path.dirname(os.path.realpath(__file__))) try: with SettingsCleaner(): activate() assert environ["DJANGO_SETTINGS_MODULE"] == "book_store.settings" finally: os.chdir(old_cwd) def test_settings_discovery_envfile_invalid_module(): # Create a .env file next to this test script with an invalid module, and make sure it fails with an ImproperlyConfigured exception script_dir = os.path.dirname(os.path.realpath(__file__)) old_cwd = os.getcwd() os.chdir(script_dir) env_path = Path(script_dir) / ".env" assert not env_path.exists(), "cowardly refusing to overwrite existing .env file" try: with open(env_path, "w") as envfile: envfile.write("DJANGO_SETTINGS_MODULE=blockbuster_video.settings") with SettingsCleaner(): load_dotenv(str(env_path)) with pytest.raises(ImproperlyConfigured): activate() finally: os.chdir(old_cwd) os.unlink(env_path) ================================================ FILE: utils/update_changelog.py ================================================ import json import pathlib import typing def main() -> None: changes: dict[str, typing.Any] = json.loads( pathlib.Path("changelog.json").read_text() ) previous_changelog: str = pathlib.Path("CHANGELOG.md").read_text() new_changelog: str = f""" # [{changes["tag_name"]}]({changes['html_url']}) {changes['created_at']} by [@{changes['author']['login']}]({changes['author']['html_url']}) ## {changes["body"]} --- {previous_changelog} """ new_changelog = new_changelog.replace("## ##", "##") pathlib.Path("CHANGELOG.md").write_text(new_changelog) if __name__ == "__main__": main()