├── .editorconfig ├── .github ├── CODEOWNERS ├── ISSUE_TEMPLATE.md ├── release-drafter.yml └── workflows │ ├── ci.yml │ ├── publish.yml │ └── release-drafter.yml ├── .gitignore ├── .travis.yml ├── AUTHORS.rst ├── CONTRIBUTING.rst ├── HISTORY.rst ├── LICENSE ├── MANIFEST.in ├── README.rst ├── django_readonly_field ├── __init__.py ├── apps.py └── compiler.py ├── docker-compose.yml ├── docs ├── Makefile ├── authors.rst ├── conf.py ├── contributing.rst ├── history.rst ├── index.rst ├── installation.rst ├── make.bat ├── readme.rst └── usage.rst ├── pyproject.toml ├── requirements.txt ├── setup.cfg ├── setup.py ├── tests ├── __init__.py ├── readonly_app │ ├── __init__.py │ ├── migrations │ │ ├── 0001_initial.py │ │ ├── 0002_sql_default.py │ │ └── __init__.py │ ├── models.py │ └── views.py ├── readonly_project │ ├── __init__.py │ └── settings.py └── test_readonly.py └── tox.ini /.editorconfig: -------------------------------------------------------------------------------- 1 | # http://editorconfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | charset = utf-8 7 | end_of_line = lf 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | 11 | [*.{py,rst,ini}] 12 | indent_style = space 13 | indent_size = 4 14 | 15 | [*.{html,css,scss,json,yml}] 16 | indent_style = space 17 | indent_size = 2 18 | 19 | [*.md] 20 | trim_trailing_whitespace = false 21 | 22 | [Makefile] 23 | indent_style = tab 24 | -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @peopledoc/python-community 2 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | * Django Readonly Field version: 2 | * Django version: 3 | * Python version: 4 | * Operating System: 5 | 6 | ### Description 7 | 8 | Describe what you were trying to get done. 9 | Tell us what happened, what went wrong, and what you expected to happen. 10 | 11 | ### What I Did 12 | 13 | ``` 14 | Paste the command(s) you ran and the output. 15 | If there was a crash, please include the traceback here. 16 | ``` 17 | -------------------------------------------------------------------------------- /.github/release-drafter.yml: -------------------------------------------------------------------------------- 1 | template: | 2 | $CHANGES 3 | 4 | ## Kudos: 5 | 6 | $CONTRIBUTORS 7 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | pull_request: 5 | push: 6 | branches: 7 | - 'master' 8 | tags: 9 | - '*' 10 | 11 | jobs: 12 | build: 13 | 14 | # When testing new Python or Django versions, one should use the 15 | # filterwarnings definition of setup.cfg to turn deprecation warnings 16 | # into errors. 17 | strategy: 18 | matrix: 19 | include: 20 | 21 | - name: Python 3.7 / Django 2.2 22 | python_version: "3.7" 23 | tox_env: py37-django22 24 | 25 | - name: Python 3.8 / Django 3.0 26 | python_version: "3.8" 27 | tox_env: py38-django30 28 | 29 | - name: Python 3.9 / Django 3.1 30 | python_version: "3.9" 31 | tox_env: py39-django31 32 | 33 | - name: Python 3.10 / Django 3.2 34 | python_version: "3.10" 35 | tox_env: py310-django32 36 | 37 | - name: Python 3.10 / Django 4.0 38 | python_version: "3.10" 39 | tox_env: py310-django40 40 | 41 | - name: Python 3.11 / Django 4.1 42 | python_version: "3.11" 43 | tox_env: py311-django41 44 | 45 | - name: Lint 46 | python_version: "3" 47 | tox_env: lint 48 | 49 | - name: Docs 50 | python_version: "3" 51 | tox_env: docs 52 | 53 | name: "${{ matrix.name }}" 54 | runs-on: ubuntu-latest 55 | 56 | services: 57 | postgres: 58 | image: postgres 59 | # Set health checks to wait until postgres has started 60 | env: 61 | POSTGRES_PASSWORD: postgres 62 | options: >- 63 | --health-cmd pg_isready 64 | --health-interval 10s 65 | --health-timeout 5s 66 | ports: 67 | - 5432:5432 68 | 69 | steps: 70 | - uses: actions/checkout@v2 71 | 72 | - name: Set up Python 73 | id: setup-python 74 | uses: actions/setup-python@v2 75 | with: 76 | python-version: ${{ matrix.python_version }} 77 | 78 | - name: Pip cache 79 | uses: actions/cache@v2 80 | with: 81 | path: | 82 | ~/.cache/ 83 | key: ${{ steps.setup-python.outputs.python-version }}-${{ hashFiles('setup.py') }} 84 | 85 | - name: Install Tox 86 | run: pip install tox 87 | 88 | - name: Run ${{ matrix.name }} 89 | run: tox -e ${{ matrix.tox_env }} 90 | env: 91 | DATABASE_URL: postgres://postgres:postgres@localhost:5432/test 92 | 93 | report-status: 94 | name: success 95 | runs-on: ubuntu-latest 96 | needs: build 97 | steps: 98 | 99 | - name: Report success 100 | run: echo 'Success !' 101 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Deploy 2 | 3 | on: 4 | push: 5 | tags: 6 | - '*' 7 | 8 | jobs: 9 | deploy: 10 | name: Publish package to PyPI 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v2 14 | 15 | - name: Set up Python 16 | id: setup-python 17 | uses: actions/setup-python@v2 18 | with: 19 | python-version: ${{ matrix.python_version }} 20 | 21 | - name: Install 22 | run: pip install build 23 | 24 | - name: Wait for tests to succeed 25 | uses: fountainhead/action-wait-for-check@v1.0.0 26 | id: wait-for-ci 27 | with: 28 | token: ${{ secrets.GITHUB_TOKEN }} 29 | checkName: success 30 | 31 | - name: Build package 32 | run: python -m build 33 | 34 | - name: Exit if CI did not succeed 35 | if: steps.wait-for-ci.outputs.conclusion != 'success' 36 | run: exit 1 37 | 38 | - name: Publish a Python distribution to PyPI 39 | uses: pypa/gh-action-pypi-publish@release/v1 40 | with: 41 | user: __token__ 42 | password: "${{ secrets.PYPI_TOKEN }}" 43 | -------------------------------------------------------------------------------- /.github/workflows/release-drafter.yml: -------------------------------------------------------------------------------- 1 | name: Release Drafter 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | 8 | jobs: 9 | update_release_draft: 10 | runs-on: ubuntu-latest 11 | steps: 12 | # Drafts the next Release notes as Pull Requests are merged into "master" 13 | - uses: release-drafter/release-drafter@v5 14 | env: 15 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.py[cod] 2 | __pycache__ 3 | 4 | # C extensions 5 | *.so 6 | 7 | # Packages 8 | *.egg 9 | *.egg-info 10 | dist 11 | build 12 | eggs 13 | parts 14 | bin 15 | var 16 | sdist 17 | develop-eggs 18 | .installed.cfg 19 | lib 20 | lib64 21 | 22 | # Installer logs 23 | pip-log.txt 24 | 25 | # Unit test / coverage reports 26 | .coverage 27 | .tox 28 | nosetests.xml 29 | htmlcov 30 | 31 | # Translations 32 | *.mo 33 | 34 | # Mr Developer 35 | .mr.developer.cfg 36 | .project 37 | .pydevproject 38 | 39 | # Pycharm/Intellij 40 | .idea 41 | 42 | # Complexity 43 | output/*.html 44 | output/*/index.html 45 | 46 | # Sphinx 47 | docs/_build 48 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | # Config file for automatic testing at travis-ci.org 2 | dist: xenial 3 | 4 | language: python 5 | 6 | services: 7 | - postgresql 8 | 9 | env: 10 | global : DATABASE_URL=postgres://postgres:@127.0.0.1:5432 11 | 12 | matrix: 13 | include: 14 | # Python version is just for the look on travis. 15 | - python: 2.7 16 | env: TOX_ENV=py27-django111 17 | 18 | - python: 3.5 19 | env: TOX_ENV=py35-django111 20 | 21 | - python: 3.6 22 | env: TOX_ENV=py36-django111 23 | 24 | - python: 3.7 25 | env: TOX_ENV=py37-django111 26 | 27 | - python: 3.5 28 | env: TOX_ENV=py35-django20 29 | 30 | - python: 3.6 31 | env: TOX_ENV=py36-django20 32 | 33 | - python: 3.7 34 | env: TOX_ENV=py37-django20 35 | 36 | - python: 3.5 37 | env: TOX_ENV=py35-django21 38 | 39 | - python: 3.6 40 | env: TOX_ENV=py36-django21 41 | 42 | - python: 3.7 43 | env: TOX_ENV=py37-django21 44 | 45 | - python: 3.5 46 | env: TOX_ENV=py35-django22 47 | 48 | - python: 3.6 49 | env: TOX_ENV=py36-django22 50 | 51 | - python: 3.7 52 | env: TOX_ENV=py37-django22 53 | 54 | - python: 3.5 55 | env: TOX_ENV=py35-djangostable 56 | 57 | - python: 3.6 58 | env: TOX_ENV=py36-djangostable 59 | 60 | - python: 3.7 61 | env: TOX_ENV=py37-djangostable 62 | 63 | - env: TOX_ENV=linters 64 | 65 | install: 66 | - pip install tox codecov 67 | 68 | script: 69 | - tox -e $TOX_ENV 70 | 71 | after_success: 72 | - codecov 73 | -------------------------------------------------------------------------------- /AUTHORS.rst: -------------------------------------------------------------------------------- 1 | ======= 2 | Credits 3 | ======= 4 | 5 | Contributors (by alphabetic order) 6 | ---------------------------------- 7 | 8 | * `ewjoachim `_ 9 | * `@brunobord `_ 10 | * `@k4nar `_ 11 | * `@zebuline `_ 12 | -------------------------------------------------------------------------------- /CONTRIBUTING.rst: -------------------------------------------------------------------------------- 1 | ============ 2 | Contributing 3 | ============ 4 | 5 | Contributions are welcome, and they are greatly appreciated! Every 6 | little bit helps, and credit will always be given. 7 | 8 | You can contribute in many ways: 9 | 10 | Types of Contributions 11 | ---------------------- 12 | 13 | Report Bugs 14 | ~~~~~~~~~~~ 15 | 16 | Report bugs at https://github.com/peopledoc/django-readonly-field/issues. 17 | 18 | If you are reporting a bug, please include: 19 | 20 | * Your operating system name and version. 21 | * Any details about your local setup that might be helpful in troubleshooting. 22 | * Detailed steps to reproduce the bug. 23 | 24 | Fix Bugs 25 | ~~~~~~~~ 26 | 27 | Look through the GitHub issues for bugs. Anything tagged with "bug" 28 | is open to whoever wants to implement it. 29 | 30 | Implement Features 31 | ~~~~~~~~~~~~~~~~~~ 32 | 33 | Look through the GitHub issues for features. Anything tagged with "feature" 34 | is open to whoever wants to implement it. 35 | 36 | Write Documentation 37 | ~~~~~~~~~~~~~~~~~~~ 38 | 39 | Django Readonly Field could always use more documentation, whether as part of the 40 | official Django Readonly Field docs, in docstrings, or even on the web in blog posts, 41 | articles, and such. 42 | 43 | Submit Feedback 44 | ~~~~~~~~~~~~~~~ 45 | 46 | The best way to send feedback is to file an issue at https://github.com/peopledoc/django-readonly-field/issues. 47 | 48 | If you are proposing a feature: 49 | 50 | * Explain in detail how it would work. 51 | * Keep the scope as narrow as possible, to make it easier to implement. 52 | * Remember that this is a volunteer-driven project, and that contributions 53 | are welcome :) 54 | 55 | Get Started! 56 | ------------ 57 | 58 | Ready to contribute? Here's how to set up `django-readonly-field` for local development. 59 | 60 | 1. Fork the `django-readonly-field` repo on GitHub. 61 | 2. Clone your fork locally:: 62 | 63 | $ git clone git@github.com:your_name_here/django-readonly-field.git 64 | 65 | 3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:: 66 | 67 | $ mkvirtualenv django-readonly-field 68 | $ cd django-readonly-field/ 69 | $ python setup.py develop 70 | 71 | 4. Create a branch for local development:: 72 | 73 | $ git checkout -b name-of-your-bugfix-or-feature 74 | 75 | Now you can make your changes locally. 76 | 77 | 5. When you're done making changes, check that your changes pass flake8 and the 78 | tests, including testing other Python versions with tox:: 79 | 80 | $ flake8 django_readonly_field tests 81 | $ python setup.py test 82 | $ tox 83 | 84 | To get flake8 and tox, just pip install them into your virtualenv. 85 | 86 | 6. Commit your changes and push your branch to GitHub:: 87 | 88 | $ git add . 89 | $ git commit -m "Your detailed description of your changes." 90 | $ git push origin name-of-your-bugfix-or-feature 91 | 92 | 7. Submit a pull request through the GitHub website. 93 | 94 | Pull Request Guidelines 95 | ----------------------- 96 | 97 | Before you submit a pull request, check that it meets these guidelines: 98 | 99 | 1. The pull request should include tests. 100 | 2. If the pull request adds functionality, the docs should be updated. Put 101 | your new functionality into a function with a docstring, and add the 102 | feature to the list in README.rst. 103 | 3. The pull request should work for Python 2.7, 3.5, 3.6 and 3.7. Check 104 | https://travis-ci.org/peopledoc/django-readonly-field/pull_requests 105 | and make sure that the tests pass for all supported Python versions. 106 | 107 | Tips 108 | ---- 109 | 110 | To run a subset of tests:: 111 | 112 | $ pytest tests/test_django_readonly_field 113 | -------------------------------------------------------------------------------- /HISTORY.rst: -------------------------------------------------------------------------------- 1 | .. :changelog: 2 | 3 | History 4 | ------- 5 | 6 | 1.0.6 (unreleased) 7 | ++++++++++++++++++ 8 | 9 | - Run tests for Django 4.1 and Python 3.11 10 | 11 | 1.0.5 (2019-04-23) 12 | ++++++++++++++++++ 13 | 14 | - Run tests for Django 2.2 and Python 3.5, 3.6 and 3.7 15 | 16 | 1.0.4 (2018-12-17) 17 | ++++++++++++++++++ 18 | 19 | - Drop support of Python 3.4 20 | - Confirm support of Python 3.7 21 | - Drop support of Django 1.8 22 | - Drop support of Django 1.9 23 | - Drop support of Django 1.10 24 | - Confirm support of Django 2.0 25 | - Confirm support of Django 2.1 26 | 27 | 28 | 1.0.3 (2018-04-26) 29 | ++++++++++++++++++ 30 | 31 | - Python 3.6 support 32 | - Multiple databases support 33 | - Github organization changed to "peopledoc" 34 | 35 | 36 | 1.0.2 (2017-09-22) 37 | ++++++++++++++++++ 38 | 39 | * Added tests for Django 1.11 40 | 41 | 1.0.1 (2016-10-19) 42 | ++++++++++++++++++ 43 | 44 | * Added support for Python 3.4 and current Django stable 45 | * Fix a thread bug that would make the package usable only for test and not for real :/ 46 | 47 | 1.0.0 (2016-09-15) 48 | ++++++++++++++++++ 49 | 50 | * First stable version 51 | 52 | 0.2.0 (2016-09-14) 53 | ++++++++++++++++++ 54 | 55 | * Rationalized the writing of readonly (vs read-only) 56 | * Defined default app config 57 | 58 | 0.1.1 (2016-09-13) 59 | ++++++++++++++++++ 60 | 61 | * CI improvements 62 | * Code linting 63 | 64 | 65 | 0.1.0 (2016-09-02) 66 | ++++++++++++++++++ 67 | 68 | * First release on PyPI. 69 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | MIT License 3 | 4 | Copyright (c) 2016, PeopleDoc 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | 8 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | 10 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include AUTHORS.rst 2 | include CONTRIBUTING.rst 3 | include HISTORY.rst 4 | include LICENSE 5 | include README.rst 6 | recursive-include django_readonly_field *.html *.png *.gif *js *.css *jpg *jpeg *svg *py 7 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ============================= 2 | Django Readonly Field 3 | ============================= 4 | 5 | .. image:: https://badge.fury.io/py/django-readonly-field.png 6 | :target: https://pypi.org/pypi/django-readonly-field 7 | 8 | .. image:: https://travis-ci.org/peopledoc/django-readonly-field.png?branch=master 9 | :target: https://travis-ci.org/peopledoc/django-readonly-field 10 | 11 | .. image:: https://img.shields.io/codecov/c/github/peopledoc/django-readonly-field/master.svg 12 | :target: https://codecov.io/github/peopledoc/django-readonly-field?branch=master 13 | 14 | Make some Django model fields readonly. In other words, it lets you tell Django to 15 | read some fields from your database, but never try to write those back. It can be 16 | useful if your fields are populated by triggers or something. 17 | 18 | Requirements 19 | ------------ 20 | 21 | + **Postgresql only** 22 | + Django, tested from 2.2 to 4.1 23 | + With Python, tested from 3.7 to 3.11 24 | 25 | Documentation 26 | ------------- 27 | 28 | The full documentation is at https://django-readonly-field.readthedocs.org. 29 | 30 | Quickstart 31 | ---------- 32 | 33 | Install Django Readonly Field:: 34 | 35 | pip install django-readonly-field 36 | 37 | In your ``settings.py`` : 38 | 39 | .. code-block:: python 40 | 41 | INSTALLED_APPS = [ 42 | # ... 43 | "django_readonly_field", 44 | ] 45 | 46 | In the model where you want some fields to be read-only: 47 | 48 | .. code-block:: python 49 | 50 | class Spaceship(models.Model): 51 | name = models.CharField(max_length=100) 52 | color = models.CharField(max_length=16) 53 | 54 | class ReadonlyMeta: 55 | readonly = ["color"] 56 | 57 | That's it. Now, Django won't try to write the ``color`` field on the database. 58 | 59 | 60 | Warning 61 | ------- 62 | 63 | Django won't try to write those fields. Consequence is that your Database 64 | **must** be ok with Django not writing those fields. They should either 65 | be nullable or have a database default or be filled by a trigger, otherwise 66 | you will get an ``IntegrityError``. 67 | 68 | Don't forget that Django model field defaults won't become database defaults. 69 | You might have to write an SQL migration for this. 70 | 71 | 72 | Running Tests 73 | -------------- 74 | 75 | You will need a usable Postgresql database in order to test the project. 76 | 77 | :: 78 | 79 | source /bin/activate 80 | export DATABASE_URL=postgres://USER:PASSWORD@HOST:PORT/NAME 81 | (myenv) $ pip install -r requirements.txt 82 | 83 | Run tests for a specific version 84 | 85 | :: 86 | 87 | (myenv) $ pytest 88 | 89 | 90 | Run tests for all versions (if tox is installed globally, you don't need a 91 | virtual environment) 92 | 93 | :: 94 | 95 | $ tox 96 | 97 | 98 | Credits 99 | --------- 100 | 101 | Tools used in rendering this package: 102 | 103 | * Cookiecutter_ 104 | * `cookiecutter-djangopackage`_ 105 | 106 | .. _Cookiecutter: https://github.com/audreyr/cookiecutter 107 | .. _`cookiecutter-djangopackage`: https://github.com/pydanny/cookiecutter-djangopackage 108 | -------------------------------------------------------------------------------- /django_readonly_field/__init__.py: -------------------------------------------------------------------------------- 1 | import django 2 | 3 | __version__ = "1.0.6dev0" 4 | 5 | 6 | if django.VERSION[:2] < (3, 2): 7 | default_app_config = "django_readonly_field.apps.Readonly" 8 | -------------------------------------------------------------------------------- /django_readonly_field/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class Readonly(AppConfig): 5 | name = 'django_readonly_field' 6 | 7 | def ready(self): 8 | from django.db import connections 9 | from django.db import utils 10 | 11 | readonly_compiler_module = "django_readonly_field.compiler" 12 | 13 | # Change the current values (this is mostly important for the tests) 14 | for c in connections: 15 | connections[c].ops.compiler_module = readonly_compiler_module 16 | 17 | original_load_backend = utils.load_backend 18 | 19 | def custom_load_backend(*args, **kwargs): 20 | backend = original_load_backend(*args, **kwargs) 21 | 22 | class ReadOnlyBackend(object): 23 | @staticmethod 24 | def DatabaseWrapper(*args2, **kwargs2): 25 | connection = backend.DatabaseWrapper(*args2, **kwargs2) 26 | connection.ops.compiler_module = readonly_compiler_module 27 | return connection 28 | 29 | return ReadOnlyBackend 30 | 31 | # Make sure all future values will be changed too 32 | # (this is mostly important for the real life) 33 | utils.load_backend = custom_load_backend 34 | -------------------------------------------------------------------------------- /django_readonly_field/compiler.py: -------------------------------------------------------------------------------- 1 | from django.db.models.sql.compiler import SQLCompiler 2 | from django.db.models.sql.compiler import SQLInsertCompiler as BaseSQLInsertCompiler # noqa 3 | from django.db.models.sql.compiler import SQLDeleteCompiler 4 | from django.db.models.sql.compiler import SQLUpdateCompiler as BaseSQLUpdateCompiler # noqa 5 | from django.db.models.sql.compiler import SQLAggregateCompiler 6 | 7 | SQLCompiler = SQLCompiler 8 | SQLDeleteCompiler = SQLDeleteCompiler 9 | SQLAggregateCompiler = SQLAggregateCompiler 10 | 11 | 12 | class ReadonlySQLCompilerMixin(object): 13 | 14 | @property 15 | def readonly_field_names(self): 16 | try: 17 | readonly_meta = getattr(self.query.model, "ReadonlyMeta") 18 | except AttributeError: 19 | return () 20 | else: 21 | fields = getattr(readonly_meta, "_cached_readonly", None) 22 | if not fields: 23 | readonly_meta._cached_readonly = fields = frozenset( 24 | getattr(readonly_meta, "readonly", ())) 25 | return fields 26 | 27 | def as_sql(self): 28 | readonly_field_names = self.readonly_field_names 29 | if readonly_field_names: 30 | self.remove_readonly_fields(readonly_field_names) 31 | return super(ReadonlySQLCompilerMixin, self).as_sql() 32 | 33 | 34 | class SQLUpdateCompiler(ReadonlySQLCompilerMixin, BaseSQLUpdateCompiler): 35 | 36 | def remove_readonly_fields(self, readonly_field_names): 37 | """ 38 | Remove the values from the query which correspond to a 39 | readonly field 40 | """ 41 | values = self.query.values 42 | 43 | # The tuple is (field, model, value) where model if used for FKs. 44 | values[:] = ( 45 | (field, _, __) for (field, _, __) in values 46 | if field.name not in readonly_field_names 47 | ) 48 | 49 | 50 | class SQLInsertCompiler(ReadonlySQLCompilerMixin, BaseSQLInsertCompiler): 51 | 52 | def _exclude_readonly_fields(self, fields, readonly_field_names): 53 | for field in fields: 54 | if field.name not in readonly_field_names: 55 | yield field 56 | 57 | def remove_readonly_fields(self, readonly_field_names): 58 | """ 59 | Remove the fields from the query which correspond to a 60 | readonly field 61 | """ 62 | fields = self.query.fields 63 | 64 | try: 65 | fields[:] = self._exclude_readonly_fields( 66 | fields, readonly_field_names) 67 | except AttributeError: 68 | # When deserializing, we might get an attribute error because this 69 | # list shoud be copied first : 70 | 71 | # "AttributeError: The return type of 'local_concrete_fields' 72 | # should never be mutated. If you want to manipulate this list for 73 | # your own use, make a copy first." 74 | 75 | self.query.fields = list(self._exclude_readonly_fields( 76 | fields, readonly_field_names)) 77 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '2.1' 2 | services: 3 | 4 | postgres: 5 | image: postgres 6 | ports: ["5432:5432"] 7 | environment: 8 | POSTGRES_DB: db 9 | POSTGRES_PASSWORD: password 10 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | 49 | clean: 50 | rm -rf $(BUILDDIR)/* 51 | 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | dirhtml: 58 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 59 | @echo 60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 61 | 62 | singlehtml: 63 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 64 | @echo 65 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 66 | 67 | pickle: 68 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 69 | @echo 70 | @echo "Build finished; now you can process the pickle files." 71 | 72 | json: 73 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 74 | @echo 75 | @echo "Build finished; now you can process the JSON files." 76 | 77 | htmlhelp: 78 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 79 | @echo 80 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 81 | ".hhp project file in $(BUILDDIR)/htmlhelp." 82 | 83 | qthelp: 84 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 85 | @echo 86 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 87 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 88 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/complexity.qhcp" 89 | @echo "To view the help file:" 90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/complexity.qhc" 91 | 92 | devhelp: 93 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 94 | @echo 95 | @echo "Build finished." 96 | @echo "To view the help file:" 97 | @echo "# mkdir -p $$HOME/.local/share/devhelp/complexity" 98 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/complexity" 99 | @echo "# devhelp" 100 | 101 | epub: 102 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 103 | @echo 104 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 105 | 106 | latex: 107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 108 | @echo 109 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 110 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 111 | "(use \`make latexpdf' here to do that automatically)." 112 | 113 | latexpdf: 114 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 115 | @echo "Running LaTeX files through pdflatex..." 116 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 117 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 118 | 119 | latexpdfja: 120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 121 | @echo "Running LaTeX files through platex and dvipdfmx..." 122 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 123 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 124 | 125 | text: 126 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 127 | @echo 128 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 129 | 130 | man: 131 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 132 | @echo 133 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 134 | 135 | texinfo: 136 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 137 | @echo 138 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 139 | @echo "Run \`make' in that directory to run these through makeinfo" \ 140 | "(use \`make info' here to do that automatically)." 141 | 142 | info: 143 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 144 | @echo "Running Texinfo files through makeinfo..." 145 | make -C $(BUILDDIR)/texinfo info 146 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 147 | 148 | gettext: 149 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 150 | @echo 151 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 152 | 153 | changes: 154 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 155 | @echo 156 | @echo "The overview file is in $(BUILDDIR)/changes." 157 | 158 | linkcheck: 159 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 160 | @echo 161 | @echo "Link check complete; look for any errors in the above output " \ 162 | "or in $(BUILDDIR)/linkcheck/output.txt." 163 | 164 | doctest: 165 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 166 | @echo "Testing of doctests in the sources finished, look at the " \ 167 | "results in $(BUILDDIR)/doctest/output.txt." 168 | 169 | xml: 170 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 171 | @echo 172 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 173 | 174 | pseudoxml: 175 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 176 | @echo 177 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 178 | -------------------------------------------------------------------------------- /docs/authors.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../AUTHORS.rst 2 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # complexity documentation build configuration file, created by 4 | # sphinx-quickstart on Tue Jul 9 22:26:36 2013. 5 | # 6 | # This file is execfile()d with the current directory set to its containing dir. 7 | # 8 | # Note that not all possible configuration values are present in this 9 | # autogenerated file. 10 | # 11 | # All configuration values have a default; values that are commented out 12 | # serve to show the default. 13 | 14 | import sys, os 15 | 16 | # If extensions (or modules to document with autodoc) are in another directory, 17 | # add these directories to sys.path here. If the directory is relative to the 18 | # documentation root, use os.path.abspath to make it absolute, like shown here. 19 | #sys.path.insert(0, os.path.abspath('.')) 20 | 21 | cwd = os.getcwd() 22 | parent = os.path.dirname(cwd) 23 | sys.path.append(parent) 24 | 25 | import django_readonly_field 26 | 27 | # -- General configuration ----------------------------------------------------- 28 | 29 | # If your documentation needs a minimal Sphinx version, state it here. 30 | #needs_sphinx = '1.0' 31 | 32 | # Add any Sphinx extension module names here, as strings. They can be extensions 33 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 34 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] 35 | 36 | # Add any paths that contain templates here, relative to this directory. 37 | templates_path = ['_templates'] 38 | 39 | # The suffix of source filenames. 40 | source_suffix = '.rst' 41 | 42 | # The encoding of source files. 43 | #source_encoding = 'utf-8-sig' 44 | 45 | # The master toctree document. 46 | master_doc = 'index' 47 | 48 | # General information about the project. 49 | project = u'Django Readonly Field' 50 | copyright = u'2016, UKG' 51 | 52 | # The version info for the project you're documenting, acts as replacement for 53 | # |version| and |release|, also used in various other places throughout the 54 | # built documents. 55 | # 56 | # The short X.Y version. 57 | version = django_readonly_field.__version__ 58 | # The full version, including alpha/beta/rc tags. 59 | release = django_readonly_field.__version__ 60 | 61 | # The language for content autogenerated by Sphinx. Refer to documentation 62 | # for a list of supported languages. 63 | #language = None 64 | 65 | # There are two options for replacing |today|: either, you set today to some 66 | # non-false value, then it is used: 67 | #today = '' 68 | # Else, today_fmt is used as the format for a strftime call. 69 | #today_fmt = '%B %d, %Y' 70 | 71 | # List of patterns, relative to source directory, that match files and 72 | # directories to ignore when looking for source files. 73 | exclude_patterns = ['_build'] 74 | 75 | # The reST default role (used for this markup: `text`) to use for all documents. 76 | #default_role = None 77 | 78 | # If true, '()' will be appended to :func: etc. cross-reference text. 79 | #add_function_parentheses = True 80 | 81 | # If true, the current module name will be prepended to all description 82 | # unit titles (such as .. function::). 83 | #add_module_names = True 84 | 85 | # If true, sectionauthor and moduleauthor directives will be shown in the 86 | # output. They are ignored by default. 87 | #show_authors = False 88 | 89 | # The name of the Pygments (syntax highlighting) style to use. 90 | pygments_style = 'sphinx' 91 | 92 | # A list of ignored prefixes for module index sorting. 93 | #modindex_common_prefix = [] 94 | 95 | # If true, keep warnings as "system message" paragraphs in the built documents. 96 | #keep_warnings = False 97 | 98 | 99 | # -- Options for HTML output --------------------------------------------------- 100 | 101 | # The theme to use for HTML and HTML Help pages. See the documentation for 102 | # a list of builtin themes. 103 | html_theme = 'alabaster' 104 | 105 | # Theme options are theme-specific and customize the look and feel of a theme 106 | # further. For a list of options available for each theme, see the 107 | # documentation. 108 | #html_theme_options = {} 109 | 110 | # Add any paths that contain custom themes here, relative to this directory. 111 | #html_theme_path = [] 112 | 113 | # The name for this set of Sphinx documents. If None, it defaults to 114 | # " v documentation". 115 | #html_title = None 116 | 117 | # A shorter title for the navigation bar. Default is the same as html_title. 118 | #html_short_title = None 119 | 120 | # The name of an image file (relative to this directory) to place at the top 121 | # of the sidebar. 122 | #html_logo = None 123 | 124 | # The name of an image file (within the static path) to use as favicon of the 125 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 126 | # pixels large. 127 | #html_favicon = None 128 | 129 | # Add any paths that contain custom static files (such as style sheets) here, 130 | # relative to this directory. They are copied after the builtin static files, 131 | # so a file named "default.css" will overwrite the builtin "default.css". 132 | html_static_path = [] 133 | 134 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 135 | # using the given strftime format. 136 | #html_last_updated_fmt = '%b %d, %Y' 137 | 138 | # If true, SmartyPants will be used to convert quotes and dashes to 139 | # typographically correct entities. 140 | #html_use_smartypants = True 141 | 142 | # Custom sidebar templates, maps document names to template names. 143 | #html_sidebars = {} 144 | 145 | # Additional templates that should be rendered to pages, maps page names to 146 | # template names. 147 | #html_additional_pages = {} 148 | 149 | # If false, no module index is generated. 150 | #html_domain_indices = True 151 | 152 | # If false, no index is generated. 153 | #html_use_index = True 154 | 155 | # If true, the index is split into individual pages for each letter. 156 | #html_split_index = False 157 | 158 | # If true, links to the reST sources are added to the pages. 159 | #html_show_sourcelink = True 160 | 161 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 162 | #html_show_sphinx = True 163 | 164 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 165 | #html_show_copyright = True 166 | 167 | # If true, an OpenSearch description file will be output, and all pages will 168 | # contain a tag referring to it. The value of this option must be the 169 | # base URL from which the finished HTML is served. 170 | #html_use_opensearch = '' 171 | 172 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 173 | #html_file_suffix = None 174 | 175 | # Output file base name for HTML help builder. 176 | htmlhelp_basename = 'django-readonly-fielddoc' 177 | 178 | 179 | # -- Options for LaTeX output -------------------------------------------------- 180 | 181 | latex_elements = { 182 | # The paper size ('letterpaper' or 'a4paper'). 183 | #'papersize': 'letterpaper', 184 | 185 | # The font size ('10pt', '11pt' or '12pt'). 186 | #'pointsize': '10pt', 187 | 188 | # Additional stuff for the LaTeX preamble. 189 | #'preamble': '', 190 | } 191 | 192 | # Grouping the document tree into LaTeX files. List of tuples 193 | # (source start file, target name, title, author, documentclass [howto/manual]). 194 | latex_documents = [ 195 | ('index', 'django-readonly-field.tex', u'Django Readonly Field Documentation', 196 | 'UKG', 'manual'), 197 | ] 198 | 199 | # The name of an image file (relative to this directory) to place at the top of 200 | # the title page. 201 | #latex_logo = None 202 | 203 | # For "manual" documents, if this is true, then toplevel headings are parts, 204 | # not chapters. 205 | #latex_use_parts = False 206 | 207 | # If true, show page references after internal links. 208 | #latex_show_pagerefs = False 209 | 210 | # If true, show URL addresses after external links. 211 | #latex_show_urls = False 212 | 213 | # Documents to append as an appendix to all manuals. 214 | #latex_appendices = [] 215 | 216 | # If false, no module index is generated. 217 | #latex_domain_indices = True 218 | 219 | 220 | # -- Options for manual page output -------------------------------------------- 221 | 222 | # One entry per manual page. List of tuples 223 | # (source start file, name, description, authors, manual section). 224 | man_pages = [ 225 | ('index', 'django-readonly-field', u'Django Readonly Field Documentation', 226 | [u'UKG'], 1) 227 | ] 228 | 229 | # If true, show URL addresses after external links. 230 | #man_show_urls = False 231 | 232 | 233 | # -- Options for Texinfo output ------------------------------------------------ 234 | 235 | # Grouping the document tree into Texinfo files. List of tuples 236 | # (source start file, target name, title, author, 237 | # dir menu entry, description, category) 238 | texinfo_documents = [ 239 | ('index', 'django-readonly-field', u'Django Readonly Field Documentation', 240 | u'UKG', 'django-readonly-field', 'One line description of project.', 241 | 'Miscellaneous'), 242 | ] 243 | 244 | # Documents to append as an appendix to all manuals. 245 | #texinfo_appendices = [] 246 | 247 | # If false, no module index is generated. 248 | #texinfo_domain_indices = True 249 | 250 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 251 | #texinfo_show_urls = 'footnote' 252 | 253 | # If true, do not generate a @detailmenu in the "Top" node's menu. 254 | #texinfo_no_detailmenu = False 255 | -------------------------------------------------------------------------------- /docs/contributing.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../CONTRIBUTING.rst 2 | -------------------------------------------------------------------------------- /docs/history.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../HISTORY.rst 2 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. complexity documentation master file, created by 2 | sphinx-quickstart on Tue Jul 9 22:26:36 2013. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to Django Readonly Field's documentation! 7 | ================================================================= 8 | 9 | Contents: 10 | 11 | .. toctree:: 12 | :maxdepth: 2 13 | 14 | readme 15 | installation 16 | usage 17 | contributing 18 | authors 19 | history 20 | -------------------------------------------------------------------------------- /docs/installation.rst: -------------------------------------------------------------------------------- 1 | ============ 2 | Installation 3 | ============ 4 | 5 | $ pip install django-readonly-field 6 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 31 | echo. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. xml to make Docutils-native XML files 37 | echo. pseudoxml to make pseudoxml-XML files for display purposes 38 | echo. linkcheck to check all external links for integrity 39 | echo. doctest to run all doctests embedded in the documentation if enabled 40 | goto end 41 | ) 42 | 43 | if "%1" == "clean" ( 44 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 45 | del /q /s %BUILDDIR%\* 46 | goto end 47 | ) 48 | 49 | 50 | %SPHINXBUILD% 2> nul 51 | if errorlevel 9009 ( 52 | echo. 53 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 54 | echo.installed, then set the SPHINXBUILD environment variable to point 55 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 56 | echo.may add the Sphinx directory to PATH. 57 | echo. 58 | echo.If you don't have Sphinx installed, grab it from 59 | echo.http://sphinx-doc.org/ 60 | exit /b 1 61 | ) 62 | 63 | if "%1" == "html" ( 64 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 65 | if errorlevel 1 exit /b 1 66 | echo. 67 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 68 | goto end 69 | ) 70 | 71 | if "%1" == "dirhtml" ( 72 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 73 | if errorlevel 1 exit /b 1 74 | echo. 75 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 76 | goto end 77 | ) 78 | 79 | if "%1" == "singlehtml" ( 80 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 81 | if errorlevel 1 exit /b 1 82 | echo. 83 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 84 | goto end 85 | ) 86 | 87 | if "%1" == "pickle" ( 88 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 89 | if errorlevel 1 exit /b 1 90 | echo. 91 | echo.Build finished; now you can process the pickle files. 92 | goto end 93 | ) 94 | 95 | if "%1" == "json" ( 96 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 97 | if errorlevel 1 exit /b 1 98 | echo. 99 | echo.Build finished; now you can process the JSON files. 100 | goto end 101 | ) 102 | 103 | if "%1" == "htmlhelp" ( 104 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 105 | if errorlevel 1 exit /b 1 106 | echo. 107 | echo.Build finished; now you can run HTML Help Workshop with the ^ 108 | .hhp project file in %BUILDDIR%/htmlhelp. 109 | goto end 110 | ) 111 | 112 | if "%1" == "qthelp" ( 113 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 114 | if errorlevel 1 exit /b 1 115 | echo. 116 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 117 | .qhcp project file in %BUILDDIR%/qthelp, like this: 118 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\complexity.qhcp 119 | echo.To view the help file: 120 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\complexity.ghc 121 | goto end 122 | ) 123 | 124 | if "%1" == "devhelp" ( 125 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished. 129 | goto end 130 | ) 131 | 132 | if "%1" == "epub" ( 133 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 134 | if errorlevel 1 exit /b 1 135 | echo. 136 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 137 | goto end 138 | ) 139 | 140 | if "%1" == "latex" ( 141 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 142 | if errorlevel 1 exit /b 1 143 | echo. 144 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 145 | goto end 146 | ) 147 | 148 | if "%1" == "latexpdf" ( 149 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 150 | cd %BUILDDIR%/latex 151 | make all-pdf 152 | cd %BUILDDIR%/.. 153 | echo. 154 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 155 | goto end 156 | ) 157 | 158 | if "%1" == "latexpdfja" ( 159 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 160 | cd %BUILDDIR%/latex 161 | make all-pdf-ja 162 | cd %BUILDDIR%/.. 163 | echo. 164 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 165 | goto end 166 | ) 167 | 168 | if "%1" == "text" ( 169 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 170 | if errorlevel 1 exit /b 1 171 | echo. 172 | echo.Build finished. The text files are in %BUILDDIR%/text. 173 | goto end 174 | ) 175 | 176 | if "%1" == "man" ( 177 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 178 | if errorlevel 1 exit /b 1 179 | echo. 180 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 181 | goto end 182 | ) 183 | 184 | if "%1" == "texinfo" ( 185 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 186 | if errorlevel 1 exit /b 1 187 | echo. 188 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 189 | goto end 190 | ) 191 | 192 | if "%1" == "gettext" ( 193 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 194 | if errorlevel 1 exit /b 1 195 | echo. 196 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 197 | goto end 198 | ) 199 | 200 | if "%1" == "changes" ( 201 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 202 | if errorlevel 1 exit /b 1 203 | echo. 204 | echo.The overview file is in %BUILDDIR%/changes. 205 | goto end 206 | ) 207 | 208 | if "%1" == "linkcheck" ( 209 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 210 | if errorlevel 1 exit /b 1 211 | echo. 212 | echo.Link check complete; look for any errors in the above output ^ 213 | or in %BUILDDIR%/linkcheck/output.txt. 214 | goto end 215 | ) 216 | 217 | if "%1" == "doctest" ( 218 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 219 | if errorlevel 1 exit /b 1 220 | echo. 221 | echo.Testing of doctests in the sources finished, look at the ^ 222 | results in %BUILDDIR%/doctest/output.txt. 223 | goto end 224 | ) 225 | 226 | if "%1" == "xml" ( 227 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 228 | if errorlevel 1 exit /b 1 229 | echo. 230 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 231 | goto end 232 | ) 233 | 234 | if "%1" == "pseudoxml" ( 235 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 236 | if errorlevel 1 exit /b 1 237 | echo. 238 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 239 | goto end 240 | ) 241 | 242 | :end 243 | -------------------------------------------------------------------------------- /docs/readme.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../README.rst 2 | -------------------------------------------------------------------------------- /docs/usage.rst: -------------------------------------------------------------------------------- 1 | ======== 2 | Usage 3 | ======== 4 | 5 | In your ``settings.py`` : 6 | 7 | .. code-block:: python 8 | 9 | INSTALLED_APPS = [ 10 | # ... 11 | "django_readonly_field", 12 | ] 13 | 14 | In the model where you want some fields to be read-only: 15 | 16 | .. code-block:: python 17 | 18 | class Spaceship(models.Model): 19 | name = models.CharField(max_length=100) 20 | color = models.CharField(max_length=16) 21 | 22 | class ReadonlyMeta: 23 | readonly = ["color"] 24 | 25 | That's it. Now, Django won't try to write the ``color`` field on the database. 26 | 27 | 28 | Warning 29 | ------- 30 | 31 | Django won't try to write those fields. Consequence is that your Database 32 | **must** be ok with Django not writing those fields. They should either 33 | be nullable or have a database default or be filled by a trigger, otherwise 34 | you will get an ``IntegrityError``. 35 | 36 | Don't forget that Django model field defaults won't become database defaults. 37 | You might have to write an SQL migration for this. 38 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools>=45", "wheel", "setuptools_scm>=6.2"] 3 | 4 | [tool.setuptools_scm] 5 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | -e .[dev] 2 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | name = django-readonly-field 3 | description = Make Django model fields readonly 4 | author = PeopleDoc 5 | author_email = peopledoc-python@ukg.com 6 | url = https://github.com/peopledoc/django-readonly-field 7 | long_description = file: README.rst 8 | keywords = django posgresql read-only 9 | license = MIT 10 | classifiers = 11 | Intended Audience :: Developers 12 | License :: OSI Approved :: MIT License 13 | Development Status :: 5 - Production/Stable 14 | Framework :: Django 15 | Framework :: Django :: 2.2 16 | Framework :: Django :: 3.0 17 | Framework :: Django :: 3.1 18 | Framework :: Django :: 3.2 19 | Framework :: Django :: 4.0 20 | Framework :: Django :: 4.1 21 | Programming Language :: Python :: 3 22 | Programming Language :: Python :: 3.7 23 | Programming Language :: Python :: 3.8 24 | Programming Language :: Python :: 3.9 25 | Programming Language :: Python :: 3.10 26 | Programming Language :: Python :: 3.11 27 | 28 | [options] 29 | zip_safe = True 30 | include_package_data = True 31 | packages = find: 32 | install_requires = 33 | Django 34 | 35 | [options.extras_require] 36 | 37 | dev = 38 | build 39 | dj_database_url 40 | flake8 41 | psycopg2 42 | pytest 43 | pytest-cov 44 | pytest-django 45 | requests 46 | sphinx 47 | tox 48 | twine 49 | 50 | [isort] 51 | profile = black 52 | 53 | [flake8] 54 | ignore = E501 55 | 56 | [wheel] 57 | universal = 1 58 | 59 | [doc8] 60 | max-line-length=88 61 | ignore-path=docs/_build 62 | 63 | 64 | [tool:pytest] 65 | DJANGO_SETTINGS_MODULE = tests.readonly_project.settings 66 | addopts = 67 | --cov-report term-missing --cov-branch --cov-report html --cov-report term 68 | --cov=django_readonly_field -vv --strict-markers -rfE -s 69 | testpaths = 70 | tests/ 71 | filterwarnings = 72 | error 73 | ignore:.*distutils Version classes are deprecated.*:DeprecationWarning 74 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | setup() 4 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peopledoc/django-readonly-field/36997cbca1ff9fa264645154ca546af36075e63c/tests/__init__.py -------------------------------------------------------------------------------- /tests/readonly_app/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peopledoc/django-readonly-field/36997cbca1ff9fa264645154ca546af36075e63c/tests/readonly_app/__init__.py -------------------------------------------------------------------------------- /tests/readonly_app/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | from django.db import migrations, models 2 | 3 | 4 | class Migration(migrations.Migration): 5 | 6 | dependencies = [ 7 | ] 8 | 9 | operations = [ 10 | migrations.CreateModel( 11 | name='Car', 12 | fields=[ 13 | ('id', models.BigAutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), 14 | ('wheel_number', models.IntegerField()), 15 | ('manufacturer', models.CharField(max_length=100)), 16 | ], 17 | ), 18 | migrations.CreateModel( 19 | name='Book', 20 | fields=[ 21 | ('id', models.BigAutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), 22 | ('ref', models.IntegerField()), 23 | ('iban', models.CharField(max_length=100)), 24 | ('name', models.CharField(max_length=250)), 25 | ], 26 | ), 27 | migrations.CreateModel( 28 | name='Bus', 29 | fields=[ 30 | ('id', models.BigAutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), 31 | ('wheel_number', models.IntegerField()), 32 | ('manufacturer', models.CharField(max_length=100)), 33 | ], 34 | ), 35 | ] 36 | -------------------------------------------------------------------------------- /tests/readonly_app/migrations/0002_sql_default.py: -------------------------------------------------------------------------------- 1 | from django.db import migrations 2 | 3 | 4 | class Migration(migrations.Migration): 5 | 6 | dependencies = [ 7 | ('readonly_app', '0001_initial'), 8 | ] 9 | 10 | operations = [ 11 | migrations.RunSQL([ 12 | '''ALTER TABLE readonly_app_car ''' 13 | '''ALTER COLUMN manufacturer SET DEFAULT 'Renault';''', 14 | 15 | '''ALTER TABLE readonly_app_bus ''' 16 | '''ALTER COLUMN wheel_number SET DEFAULT 22;''' 17 | 18 | '''ALTER TABLE readonly_app_book ''' 19 | '''ALTER COLUMN iban SET DEFAULT '1234-abcd';''', 20 | 21 | '''ALTER TABLE readonly_app_book ''' 22 | '''ALTER COLUMN ref SET DEFAULT 123456789;''']) 23 | ] 24 | -------------------------------------------------------------------------------- /tests/readonly_app/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peopledoc/django-readonly-field/36997cbca1ff9fa264645154ca546af36075e63c/tests/readonly_app/migrations/__init__.py -------------------------------------------------------------------------------- /tests/readonly_app/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | 4 | class Car(models.Model): 5 | 6 | wheel_number = models.IntegerField() 7 | manufacturer = models.CharField(max_length=100) 8 | 9 | def __str__(self): 10 | return "{car.manufacturer} Car with {car.wheel_number} wheels".format( 11 | car=self) 12 | 13 | class ReadonlyMeta: 14 | readonly = ["manufacturer"] 15 | 16 | 17 | class Book(models.Model): 18 | """ 19 | A completely different model 20 | """ 21 | ref = models.IntegerField() 22 | iban = models.CharField(max_length=100) 23 | name = models.CharField(max_length=250) 24 | 25 | def __str__(self): 26 | return "{book.name} (ref: {book.ref}, iban: {book.iban})" 27 | 28 | class ReadonlyMeta: 29 | readonly = ["ref", "iban"] 30 | 31 | 32 | class Bus(models.Model): 33 | """ 34 | This is the same model as Car but with readonly fields the other way 35 | around to make sure we don't mix them up. 36 | """ 37 | 38 | wheel_number = models.IntegerField() 39 | manufacturer = models.CharField(max_length=100) 40 | 41 | def __str__(self): 42 | return "{car.manufacturer} Bus with {car.wheel_number} wheels".format( 43 | car=self) 44 | 45 | class ReadonlyMeta: 46 | readonly = ["wheel_number"] 47 | -------------------------------------------------------------------------------- /tests/readonly_app/views.py: -------------------------------------------------------------------------------- 1 | from django import http 2 | from django.urls import path 3 | 4 | from .models import Car 5 | 6 | 7 | def test_view(request): 8 | car = Car.objects.create(manufacturer="Honda", wheel_number=3) 9 | car.refresh_from_db() 10 | 11 | valid = car.manufacturer == "Renault" 12 | return http.HttpResponse( 13 | content_type="text/plain", 14 | content="OK" if valid else "Fail") 15 | 16 | 17 | urlpatterns = [path("", test_view)] 18 | -------------------------------------------------------------------------------- /tests/readonly_project/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peopledoc/django-readonly-field/36997cbca1ff9fa264645154ca546af36075e63c/tests/readonly_project/__init__.py -------------------------------------------------------------------------------- /tests/readonly_project/settings.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | 4 | import dj_database_url 5 | 6 | if "DATABASE_URL" not in os.environ or \ 7 | not os.environ["DATABASE_URL"].startswith("postgres://"): 8 | print("\n".join( 9 | "It seems you have not configured the path to your PGSQL database", 10 | "To do so, use the DATABASE_URL environment variable like this :", 11 | "", 12 | " DATABASE_URL=postgres://USER:PASSWORD@HOST:PORT/NAME", 13 | "", 14 | "(where all optional parts can be omited to get their default value))" 15 | )) 16 | sys.exit(1) 17 | 18 | DEBUG = True 19 | USE_TZ = True 20 | DATABASES = {"default": dj_database_url.config()} 21 | INSTALLED_APPS = [ 22 | "django.contrib.auth", 23 | "django.contrib.contenttypes", 24 | "django.contrib.sites", 25 | "django_readonly_field", 26 | "tests.readonly_app", 27 | ] 28 | STATIC_URL = "/static/" 29 | SITE_ID = 1 30 | MIDDLEWARE_CLASSES = () 31 | LOGGING = {} 32 | SECRET_KEY = "yay" 33 | ROOT_URLCONF = "tests.readonly_app.views" 34 | DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" 35 | -------------------------------------------------------------------------------- /tests/test_readonly.py: -------------------------------------------------------------------------------- 1 | from contextlib import contextmanager 2 | import json 3 | 4 | import requests 5 | import six 6 | 7 | from django.test import TestCase 8 | from django.test import LiveServerTestCase 9 | from django.db import connection 10 | from django.test.utils import CaptureQueriesContext 11 | from django.core import serializers 12 | 13 | # Create your tests here. 14 | from tests.readonly_app.models import Car 15 | from tests.readonly_app.models import Bus 16 | from tests.readonly_app.models import Book 17 | 18 | 19 | class ReadonlyFieldTest(TestCase): 20 | 21 | # Note : the default for fields is in the file 0002_sql_default.py 22 | # Default values are : 23 | # Car: manufacturer = "Renault" 24 | # Bus: wheel_number = 22 25 | # Book: iban = "1234-abcd", ref = 123456789 26 | 27 | @classmethod 28 | def setUpTestData(cls): 29 | cls.peugeot_car = Car.objects.create(wheel_number=5) 30 | connection.cursor().execute( 31 | "UPDATE readonly_app_car " 32 | "SET manufacturer='Peugeot' WHERE id=%s", 33 | [cls.peugeot_car.pk]) 34 | 35 | def setUp(self): 36 | self.peugeot_car.refresh_from_db() 37 | 38 | @contextmanager 39 | def assertSQLQueries(self, model=None, check_other_fields=True): 40 | """ 41 | Asserts that the SQL from the queries don't mention 42 | the readonly field. SELECTS are authorized, though. 43 | model allow you to specify the model for which readonly 44 | fields will be checked 45 | """ 46 | model = model or Car 47 | readonly_fields = model.ReadonlyMeta.readonly 48 | with CaptureQueriesContext(connection=connection) as capture: 49 | yield capture 50 | 51 | unchecked_queries = frozenset("SELECT SAVEPOINT RELEASE".split()) 52 | 53 | for query in self._filter_queries(capture, exclude=unchecked_queries): 54 | 55 | for field in readonly_fields: 56 | self.assertNotIn(field, query['sql']) 57 | 58 | if check_other_fields: 59 | fields = {field.name 60 | for field in model._meta.fields 61 | if not field.primary_key} 62 | read_write_fields = fields - frozenset(readonly_fields) 63 | for field in read_write_fields: 64 | self.assertIn(field, query['sql']) 65 | 66 | def _filter_queries(self, capture, include=None, exclude=None): 67 | for query in capture.captured_queries: 68 | command = query['sql'].split()[0] 69 | if include: 70 | if command in include: 71 | yield query 72 | if exclude: 73 | if command not in exclude: 74 | yield query 75 | 76 | def assertNumCommands(self, capture, command, count): 77 | queries = list(self._filter_queries(capture, include={command})) 78 | num_queries = len(queries) 79 | self.assertEqual( 80 | num_queries, 81 | count, 82 | "{num_queries} {command} query(ies) found. " 83 | "Expected {count}. \n Queries: {queries}".format( 84 | num_queries=num_queries, command=command, 85 | count=count, queries="\n".join( 86 | q['sql'] for q in queries))) 87 | 88 | def test_create(self): 89 | # Create, don't specify the readonly field 90 | with self.assertSQLQueries(): 91 | car = Car.objects.create(wheel_number=4) 92 | 93 | car.refresh_from_db() 94 | 95 | self.assertEqual(car.wheel_number, 4) 96 | self.assertEqual(car.manufacturer, "Renault") 97 | 98 | # Create, do specify the readonly field 99 | with self.assertSQLQueries(): 100 | car = Car.objects.create(manufacturer="Honda", wheel_number=3) 101 | 102 | car.refresh_from_db() 103 | self.assertEqual(car.manufacturer, "Renault") 104 | self.assertEqual(car.wheel_number, 3) 105 | 106 | def test_save(self): 107 | # Save a new instance, don't specify the readonly field 108 | with self.assertSQLQueries(): 109 | car = Car(wheel_number=3) 110 | car.save() 111 | 112 | car.refresh_from_db() 113 | 114 | self.assertEqual(car.manufacturer, "Renault") 115 | self.assertEqual(car.wheel_number, 3) 116 | 117 | # Save a new instance, do specify the readonly field 118 | with self.assertSQLQueries(): 119 | car = Car(wheel_number=3, manufacturer="Opel") 120 | car.save() 121 | 122 | car.refresh_from_db() 123 | self.assertEqual(car.manufacturer, "Renault") 124 | self.assertEqual(car.wheel_number, 3) 125 | 126 | def test_save_update(self): 127 | # Save an existing instance 128 | car = self.peugeot_car 129 | 130 | with self.assertSQLQueries(): 131 | car.save() 132 | 133 | car.refresh_from_db() 134 | self.assertEqual(car.manufacturer, "Peugeot") 135 | self.assertEqual(car.wheel_number, 5) 136 | 137 | # Save an existing instance, don't specify the readonly field 138 | with self.assertSQLQueries(): 139 | car.wheel_number = 7 140 | car.save() 141 | 142 | car.refresh_from_db() 143 | self.assertEqual(car.manufacturer, "Peugeot") 144 | self.assertEqual(car.wheel_number, 7) 145 | 146 | # Save an existing instance, do specify the readonly field 147 | with self.assertSQLQueries(): 148 | car.manufacturer = "Citroen" 149 | car.save() 150 | 151 | car.refresh_from_db() 152 | self.assertEqual(car.manufacturer, "Peugeot") 153 | self.assertEqual(car.wheel_number, 7) 154 | 155 | def test_update(self): 156 | # Update, don't specify the readonly field 157 | car = self.peugeot_car 158 | with self.assertSQLQueries(): 159 | Car.objects.filter(pk=car.pk).update(wheel_number=12) 160 | 161 | car.refresh_from_db() 162 | self.assertEqual(car.manufacturer, "Peugeot") 163 | self.assertEqual(car.wheel_number, 12) 164 | 165 | # Update, do specify the readonly field 166 | with self.assertSQLQueries(): 167 | Car.objects.filter(pk=car.pk).update(manufacturer="Ferrari") 168 | 169 | car.refresh_from_db() 170 | self.assertEqual(car.manufacturer, "Peugeot") 171 | self.assertEqual(car.wheel_number, 12) 172 | 173 | # Update both 174 | with self.assertSQLQueries(): 175 | Car.objects.filter(pk=car.pk).update( 176 | manufacturer="Ferrari", wheel_number=52) 177 | 178 | car.refresh_from_db() 179 | self.assertEqual(car.manufacturer, "Peugeot") 180 | self.assertEqual(car.wheel_number, 52) 181 | 182 | def test_get_or_create(self): 183 | # get_or_create, don't specify the readonly field 184 | with self.assertSQLQueries(): 185 | car, __ = Car.objects.get_or_create(wheel_number=3) 186 | 187 | car.refresh_from_db() 188 | self.assertEqual(car.manufacturer, "Renault") 189 | 190 | # get_or_create, do specify the readonly field 191 | with self.assertSQLQueries(): 192 | car, __ = Car.objects.get_or_create( 193 | wheel_number=3, 194 | defaults={"manufacturer": "Volkswagen"}) 195 | 196 | car.refresh_from_db() 197 | self.assertEqual(car.manufacturer, "Renault") 198 | self.assertEqual(car.wheel_number, 3) 199 | 200 | # (we're not testing the get part because it doesn't involve a write) 201 | 202 | def test_bulk_create(self): 203 | 204 | # bulk_create, do and don't specify the readonly field 205 | latest_car_pk = Car.objects.latest("pk").pk 206 | queryset = Car.objects.filter(pk__gt=latest_car_pk) 207 | 208 | with self.assertSQLQueries(): 209 | Car.objects.bulk_create([ 210 | Car(wheel_number=3), 211 | Car(wheel_number=3, manufacturer="Nissan")]) 212 | 213 | # 2 cars were saved 214 | self.assertEqual(queryset.count(), 2) 215 | 216 | # No car exists with "Nissan" 217 | self.assertFalse( 218 | queryset.filter(manufacturer="Nissan").exists()) 219 | 220 | # All cars have 3 wheels (what ?!) 221 | self.assertTrue(all( 222 | car.wheel_number == 3 for car in queryset)) 223 | 224 | def test_serialize(self): 225 | serialized = json.loads(serializers.serialize( 226 | "json", 227 | Car.objects.filter(id=self.peugeot_car.id))) 228 | 229 | self.assertEqual(len(serialized), 1) 230 | 231 | dict_car, = serialized 232 | 233 | self.assertIn("wheel_number", dict_car["fields"]) 234 | self.assertIn("manufacturer", dict_car["fields"]) 235 | 236 | def test_deserialize(self): 237 | pk = Car.objects.latest("id").id + 1 238 | json_car = json.dumps([{"model": "readonly_app.car", 239 | "pk": pk, 240 | "fields": {"wheel_number": 12, 241 | "manufacturer": "Volvo"}}]) 242 | 243 | # Check that the save works 244 | with self.assertSQLQueries(Car) as capture: 245 | deserialized = serializers.deserialize("json", json_car) 246 | 247 | car, = deserialized 248 | car.save() 249 | 250 | # Because a pk is specified, Django will try to do an UPDATE and then 251 | # an INSERT when the UPDATE returns with 0 rows affected 252 | self.assertNumCommands(capture, command="UPDATE", count=1) 253 | self.assertNumCommands(capture, command="INSERT", count=1) 254 | 255 | car = Car.objects.get(pk=pk) 256 | self.assertEqual(car.wheel_number, 12) 257 | self.assertEqual(car.manufacturer, "Renault") 258 | 259 | json_car = json_car.replace("12", "14") 260 | # Check that the UPDATE works 261 | with self.assertSQLQueries(Car) as capture: 262 | deserialized = serializers.deserialize("json", json_car) 263 | 264 | car, = deserialized 265 | car.save() 266 | 267 | self.assertNumCommands(capture, command="UPDATE", count=1) 268 | self.assertNumCommands(capture, command="INSERT", count=0) 269 | 270 | car = Car.objects.get(pk=pk) 271 | self.assertEqual(car.wheel_number, 14) 272 | self.assertEqual(car.manufacturer, "Renault") 273 | 274 | def test_several_models(self): 275 | 276 | # We make sure that using several models together don't result 277 | # in an error. In particular, car and bus have properties of the 278 | # same name but not the same "readonly" state. 279 | 280 | # First without specifying the readonly field 281 | with self.assertSQLQueries(Car): 282 | car = Car.objects.create(wheel_number=4) 283 | with self.assertSQLQueries(Bus): 284 | bus = Bus.objects.create(manufacturer="Audi") 285 | with self.assertSQLQueries(Book): 286 | book = Book.objects.create(name="Farenheit 411") 287 | 288 | car.refresh_from_db() 289 | self.assertEqual(car.manufacturer, "Renault") 290 | self.assertEqual(car.wheel_number, 4) 291 | 292 | bus.refresh_from_db() 293 | self.assertEqual(bus.wheel_number, 22) 294 | self.assertEqual(bus.manufacturer, "Audi") 295 | 296 | book.refresh_from_db() 297 | self.assertEqual(book.name, "Farenheit 411") 298 | self.assertEqual(book.ref, 123456789) 299 | self.assertEqual(book.iban, "1234-abcd") 300 | 301 | # Then, specifying the readonly field 302 | with self.assertSQLQueries(Car): 303 | car = Car.objects.create( 304 | wheel_number=4, manufacturer="Lamborghini") 305 | with self.assertSQLQueries(Bus): 306 | bus = Bus.objects.create( 307 | manufacturer="Audi", wheel_number=17) 308 | with self.assertSQLQueries(Book): 309 | book = Book.objects.create( 310 | name="Harry Potter", ref=4321, iban="zyxw-9876") 311 | 312 | car.refresh_from_db() 313 | self.assertEqual(car.manufacturer, "Renault") 314 | self.assertEqual(car.wheel_number, 4) 315 | 316 | bus.refresh_from_db() 317 | self.assertEqual(bus.wheel_number, 22) 318 | self.assertEqual(bus.manufacturer, "Audi") 319 | 320 | book.refresh_from_db() 321 | self.assertEqual(book.name, "Harry Potter") 322 | self.assertEqual(book.ref, 123456789) 323 | self.assertEqual(book.iban, "1234-abcd") 324 | 325 | 326 | class ReadonlyFieldRunserverTest(LiveServerTestCase): 327 | def test_run_server(self): 328 | self.assertEqual( 329 | requests.get(self.live_server_url).content, 330 | six.b("OK")) 331 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = 3 | py37-django22 4 | py38-django30 5 | py39-django31, 6 | py310-django{32,40} 7 | py311-django41, 8 | linters 9 | docs 10 | 11 | [testenv] 12 | usedevelop = True 13 | extras = dev 14 | setenv = 15 | DATABASE_URL = {env:DATABASE_URL:postgres://postgres:password@127.0.0.1:5432/db} 16 | deps = 17 | django22: psycopg2<2.9 # https://github.com/django/django/commit/837ffcfa681d0f65f444d881ee3d69aec23770be 18 | django30: psycopg2<2.9 # https://github.com/django/django/commit/837ffcfa681d0f65f444d881ee3d69aec23770be 19 | 20 | django22: Django==2.2.* 21 | django30: Django==3.0.* 22 | django31: Django==3.1.* 23 | django32: Django==3.2.* 24 | django40: Django==4.0.* 25 | django41: Django==4.1.* 26 | djangostable: Django 27 | commands = 28 | python --version 29 | pip freeze -l 30 | pytest 31 | 32 | # Dedicated linter tox target 33 | [testenv:lint] 34 | deps = 35 | # Does not need any other requirement 36 | flake8>=2.1.0 37 | commands = 38 | flake8 django_readonly_field tests 39 | 40 | [testenv:docs] 41 | allowlist_externals = 42 | make 43 | commands = 44 | make -C docs clean html 45 | --------------------------------------------------------------------------------