├── .gitignore ├── .travis.yml ├── AUTHORS.rst ├── CONTRIBUTING.rst ├── HISTORY.rst ├── LICENSE ├── MANIFEST.in ├── Makefile ├── README.rst ├── docs ├── Makefile ├── authors.rst ├── conf.py ├── contributing.rst ├── history.rst ├── index.rst ├── installation.rst ├── make.bat ├── readme.rst └── usage.rst ├── field_history ├── __init__.py ├── admin.py ├── json_nested_serializer.py ├── management │ ├── __init__.py │ └── commands │ │ ├── __init__.py │ │ ├── createinitialfieldhistory.py │ │ └── renamefieldhistory.py ├── managers.py ├── middleware.py ├── migrations │ ├── 0001_initial.py │ ├── 0002_auto_20160413_1824.py │ └── __init__.py ├── models.py └── tracker.py ├── manage.py ├── requirements-test.txt ├── requirements_dev.txt ├── runtests.py ├── setup.cfg ├── setup.py └── tests ├── __init__.py ├── migrations ├── 0001_initial.py └── __init__.py ├── models.py ├── tests.py ├── urls.py └── views.py /.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 | # Complexity 40 | output/*.html 41 | output/*/index.html 42 | 43 | # Sphinx 44 | docs/_build -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | 3 | python: 4 | - 2.7 5 | - 3.4 6 | - 3.5 7 | - 3.6 8 | - 3.7 9 | - 3.8 10 | 11 | before_install: 12 | - pip install coveralls 13 | 14 | install: 15 | - pip install Django==${DJANGO} 16 | - pip install -e . 17 | - pip install -r requirements-test.txt 18 | 19 | script: make test 20 | 21 | env: 22 | - DJANGO=1.11.27 23 | - DJANGO=2.0.13 24 | - DJANGO=2.1.15 25 | - DJANGO=2.2.9 26 | - DJANGO=3.0.2 27 | 28 | matrix: 29 | exclude: 30 | - python: 3.8 31 | env: DJANGO=1.11.27 32 | - python: 2.7 33 | env: DJANGO=2.0.13 34 | - python: 3.8 35 | env: DJANGO=2.0.13 36 | - python: 2.7 37 | env: DJANGO=2.1.15 38 | - python: 3.4 39 | env: DJANGO=2.1.15 40 | - python: 3.8 41 | env: DJANGO=2.1.15 42 | - python: 2.7 43 | env: DJANGO=2.2.9 44 | - python: 3.4 45 | env: DJANGO=2.2.9 46 | - python: 2.7 47 | env: DJANGO=3.0.2 48 | - python: 3.4 49 | env: DJANGO=3.0.2 50 | - python: 3.5 51 | env: DJANGO=3.0.2 52 | 53 | after_success: 54 | - coveralls 55 | -------------------------------------------------------------------------------- /AUTHORS.rst: -------------------------------------------------------------------------------- 1 | ======= 2 | Credits 3 | ======= 4 | 5 | Development Lead 6 | ---------------- 7 | 8 | * Grant McConnaughey 9 | 10 | Contributors 11 | ------------ 12 | 13 | * Boris Shifrin 14 | * Matheus Cansian 15 | 16 | Background 17 | ---------- 18 | 19 | The ``FieldHistoryTracker`` class in this project is based off of the ``FieldTracker`` class from `django-model-utils `_. The following authors contributed to ``FieldTracker``: 20 | 21 | * Trey Hunner 22 | * Matthew Schinckel 23 | * Mikhail Silonov 24 | * Carl Meyer 25 | * @bboogaard 26 | -------------------------------------------------------------------------------- /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/grantmcconnaughey/django-field-history/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-field-history could always use more documentation, whether as part of the 40 | official django-field-history 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/grantmcconnaughey/django-field-history/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-field-history` for local development. 59 | 60 | 1. Fork the `django-field-history` repo on GitHub. 61 | 2. Clone your fork locally:: 62 | 63 | $ git clone git@github.com:your_name_here/django-field-history.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-field-history 68 | $ cd django-field-history/ 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:: 79 | 80 | $ flake8 field_history 81 | $ python runtests.py tests 82 | 83 | 6. Commit your changes and push your branch to GitHub:: 84 | 85 | $ git add . 86 | $ git commit -m "Your detailed description of your changes." 87 | $ git push origin name-of-your-bugfix-or-feature 88 | 89 | 7. Submit a pull request through the GitHub website. 90 | 91 | Pull Request Guidelines 92 | ----------------------- 93 | 94 | Before you submit a pull request, check that it meets these guidelines: 95 | 96 | 1. The pull request should include tests. 97 | 2. If the pull request adds functionality, the docs should be updated. Put 98 | your new functionality into a function with a docstring, and add the 99 | feature to the list in README.rst. 100 | 3. The pull request should work for Python 2.7 and 3.2+, and for Django 1.8+. Check 101 | https://travis-ci.org/grantmcconnaughey/django-field-history/pull_requests 102 | and make sure that the tests pass for all supported Python versions. 103 | 104 | Tips 105 | ---- 106 | 107 | To run a subset of tests:: 108 | 109 | $ python -m unittest tests.tests 110 | -------------------------------------------------------------------------------- /HISTORY.rst: -------------------------------------------------------------------------------- 1 | .. :changelog: 2 | 3 | History 4 | ------- 5 | 6 | 0.8.0 (January 5, 2020) 7 | +++++++++++++++++++++++ 8 | * Added support for Django 2.2 and 3.0 9 | * Added support for Python 3.8 10 | 11 | 0.7.0 (September 3, 2018) 12 | +++++++++++++++++++++++++ 13 | * Added support for Django 2.0 and 2.1 14 | * Added support for Python 3.7 15 | * Dropped support for Django 1.7 through 1.10 16 | * Dropped support for Python 3.2 and 3.3 17 | * Fixed generic primary key bug with `createinitialfieldhistory` command (#20) 18 | 19 | 0.6.0 (December 22, 2016) 20 | +++++++++++++++++++++++++ 21 | * Added Django 1.10 compatibility. 22 | * Added MySQL compatibility. 23 | * Fixed issue that would duplicate tracked fields. 24 | 25 | 0.5.0 (April 16, 2016) 26 | ++++++++++++++++++++++ 27 | * Added the ability to track field history of parent models. 28 | * Added Django 1.7 compatibility. 29 | 30 | 0.4.0 (February 24, 2016) 31 | +++++++++++++++++++++++++ 32 | * Added a way to automatically store the logged in user on ``FieldHistory.user``. 33 | 34 | 0.3.0 (February 20, 2016) 35 | +++++++++++++++++++++++++ 36 | 37 | * ``FieldHistory`` objects are now created using ``bulk_create``, which means only one query will be executed, even when changing multiple fields at the same time. 38 | * Added a way to store which user updated a field. 39 | * Added ``get_latest_by`` to ``FieldHistory`` Meta options so ``.latest()`` and ``.earliest()`` can be used. 40 | * Added ``createinitialfieldhistory`` management command. 41 | * Added ``renamefieldhistory`` management command. 42 | 43 | 0.2.0 (February 17, 2016) 44 | +++++++++++++++++++++++++ 45 | 46 | * First release on PyPI. 47 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2016, Grant McConnaughey 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 5 | 6 | * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 7 | 8 | * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 9 | 10 | * Neither the name of django-field-history nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 11 | 12 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include AUTHORS.rst 2 | include CONTRIBUTING.rst 3 | include HISTORY.rst 4 | include LICENSE 5 | include README.rst 6 | recursive-include field_history *.html *.png *.gif *js *.css *jpg *jpeg *svg *py 7 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: clean-pyc clean-build docs 2 | 3 | help: 4 | @echo "clean-build - remove build artifacts" 5 | @echo "clean-pyc - remove Python file artifacts" 6 | @echo "lint - check style with flake8" 7 | @echo "test - run tests quickly with the default Python" 8 | @echo "coverage - check code coverage quickly with the default Python" 9 | @echo "docs - generate Sphinx HTML documentation, including API docs" 10 | @echo "release - package and upload a release" 11 | @echo "sdist - package" 12 | 13 | clean: clean-build clean-pyc 14 | 15 | clean-build: 16 | rm -fr build/ 17 | rm -fr dist/ 18 | rm -fr *.egg-info 19 | 20 | clean-pyc: 21 | find . -name '*.pyc' -exec rm -f {} + 22 | find . -name '*.pyo' -exec rm -f {} + 23 | find . -name '*~' -exec rm -f {} + 24 | 25 | migrations: 26 | python manage.py makemigrations field_history 27 | 28 | lint: 29 | flake8 30 | 31 | test: lint 32 | coverage run --source field_history runtests.py tests 33 | 34 | coverage: 35 | coverage run --source field_history runtests.py tests 36 | coverage report -m 37 | coverage html 38 | open htmlcov/index.html 39 | 40 | docs: 41 | rm -f docs/django-field-history.rst 42 | rm -f docs/modules.rst 43 | sphinx-apidoc -o docs/ field_history 44 | $(MAKE) -C docs clean 45 | $(MAKE) -C docs html 46 | open docs/_build/html/index.html 47 | 48 | release: clean 49 | python setup.py sdist 50 | python setup.py bdist_wheel 51 | twine upload dist/* 52 | 53 | sdist: clean 54 | python setup.py sdist 55 | ls -l dist 56 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ==================== 2 | django-field-history 3 | ==================== 4 | 5 | .. image:: https://badge.fury.io/py/django-field-history.svg 6 | :target: https://badge.fury.io/py/django-field-history 7 | 8 | .. image:: https://readthedocs.org/projects/django-field-history/badge/?version=latest 9 | :target: https://django-field-history.readthedocs.io/en/latest/?badge=latest 10 | :alt: Documentation Status 11 | 12 | .. image:: https://travis-ci.org/grantmcconnaughey/django-field-history.svg?branch=master 13 | :target: https://travis-ci.org/grantmcconnaughey/django-field-history 14 | 15 | .. image:: https://coveralls.io/repos/github/grantmcconnaughey/django-field-history/badge.svg?branch=master 16 | :target: https://coveralls.io/github/grantmcconnaughey/django-field-history?branch=master 17 | 18 | A Django app to track changes to a model field. For Python 2.7/3.4+ and Django 1.11/2.0+. 19 | 20 | Other similar apps are `django-reversion `_ and `django-simple-history `_, which track *all* model fields. 21 | 22 | +------------------------+----------------------+------------------+----------------------------------+ 23 | | Project | django-field-history | django-reversion | django-simple-history | 24 | +------------------------+----------------------+------------------+----------------------------------+ 25 | | Admin Integration | N/A | Yes | Yes | 26 | +------------------------+----------------------+------------------+----------------------------------+ 27 | | All/Some fields | Some | Some | All | 28 | +------------------------+----------------------+------------------+----------------------------------+ 29 | | Object History | No | Yes | Yes | 30 | +------------------------+----------------------+------------------+----------------------------------+ 31 | | Model History | N/A | No | Yes | 32 | +------------------------+----------------------+------------------+----------------------------------+ 33 | | Multi-object Revisions | N/A | Yes | No | 34 | +------------------------+----------------------+------------------+----------------------------------+ 35 | | Extra Model Manager | Yes | No | Yes | 36 | +------------------------+----------------------+------------------+----------------------------------+ 37 | | Model Registry | No | Yes | No | 38 | +------------------------+----------------------+------------------+----------------------------------+ 39 | | Django View Helpers | No | Yes | No | 40 | +------------------------+----------------------+------------------+----------------------------------+ 41 | | Manager Helper Methods | N/A | Yes | Yes (``as_of``, ``most_recent``) | 42 | +------------------------+----------------------+------------------+----------------------------------+ 43 | | MySQL Support | Extra config | Complete | Complete | 44 | +------------------------+----------------------+------------------+----------------------------------+ 45 | 46 | Documentation 47 | ------------- 48 | 49 | The full documentation is at https://django-field-history.readthedocs.io. 50 | 51 | Features 52 | -------- 53 | 54 | * Keeps a history of all changes to a particular model's field. 55 | * Stores the field's name, value, date and time of change, and the user that changed it. 56 | * Works with all model field types (except ``ManyToManyField``). 57 | 58 | Quickstart 59 | ---------- 60 | 61 | Install django-field-history:: 62 | 63 | pip install django-field-history 64 | 65 | Be sure to put it in INSTALLED_APPS. 66 | 67 | .. code-block:: python 68 | 69 | INSTALLED_APPS = [ 70 | # other apps... 71 | 'field_history', 72 | ] 73 | 74 | Then add it to your models. 75 | 76 | .. code-block:: python 77 | 78 | from field_history.tracker import FieldHistoryTracker 79 | 80 | class PizzaOrder(models.Model): 81 | STATUS_CHOICES = ( 82 | ('ORDERED', 'Ordered'), 83 | ('COOKING', 'Cooking'), 84 | ('COMPLETE', 'Complete'), 85 | ) 86 | status = models.CharField(max_length=64, choices=STATUS_CHOICES) 87 | 88 | field_history = FieldHistoryTracker(['status']) 89 | 90 | Now each time you change the order's status field information about that change will be stored in the database. 91 | 92 | .. code-block:: python 93 | 94 | from field_history.models import FieldHistory 95 | 96 | # No FieldHistory objects yet 97 | assert FieldHistory.objects.count() == 0 98 | 99 | # Creating an object will make one 100 | pizza_order = PizzaOrder.objects.create(status='ORDERED') 101 | assert FieldHistory.objects.count() == 1 102 | 103 | # This object has some fields on it 104 | history = FieldHistory.objects.get() 105 | assert history.object == pizza_order 106 | assert history.field_name == 'status' 107 | assert history.field_value == 'ORDERED' 108 | assert history.date_created is not None 109 | 110 | # You can query FieldHistory using the get_{field_name}_history() 111 | # method added to your model 112 | histories = pizza_order.get_status_history() 113 | assert list(FieldHistory.objects.all()) == list(histories) 114 | 115 | # Or using the custom FieldHistory manager 116 | histories2 = FieldHistory.objects.get_for_model_and_field(pizza_order, 'status') 117 | assert list(histories) == list(histories2) 118 | 119 | # Updating that particular field creates a new FieldHistory 120 | pizza_order.status = 'COOKING' 121 | pizza_order.save() 122 | assert FieldHistory.objects.count() == 2 123 | 124 | updated_history = histories.latest() 125 | assert updated_history.object == pizza_order 126 | assert updated_history.field_name == 'status' 127 | assert updated_history.field_value == 'COOKING' 128 | assert updated_history.date_created is not None 129 | 130 | Management Commands 131 | ------------------- 132 | 133 | django-field-history comes with a few management commands. 134 | 135 | createinitialfieldhistory 136 | +++++++++++++++++++++++++ 137 | 138 | This command will inspect all of the models in your application and create ``FieldHistory`` objects for the models that have a ``FieldHistoryTracker``. Run this the first time you install django-field-history. 139 | 140 | :: 141 | 142 | python manage.py createinitialfieldhistory 143 | 144 | renamefieldhistory 145 | ++++++++++++++++++ 146 | 147 | Use this command after changing a model field name of a field you track with ``FieldHistoryTracker``:: 148 | 149 | python manage.py renamefieldhistory --model=app_label.model_name --from_field=old_field_name --to_field=new_field_name 150 | 151 | For instance, if you have this model: 152 | 153 | .. code-block:: python 154 | 155 | class Person(models.Model): 156 | username = models.CharField(max_length=255) 157 | 158 | field_history = FieldHistoryTracker(['username']) 159 | 160 | And you change the ``username`` field name to ``handle``: 161 | 162 | .. code-block:: python 163 | 164 | class Person(models.Model): 165 | handle = models.CharField(max_length=255) 166 | 167 | field_history = FieldHistoryTracker(['handle']) 168 | 169 | You will need to also update the ``field_name`` value in all ``FieldHistory`` objects that point to this model:: 170 | 171 | python manage.py renamefieldhistory --model=myapp.Person --from_field=username --to_field=handle 172 | 173 | Storing Which User Changed the Field 174 | ------------------------------------ 175 | 176 | There are two ways to store the user that changed your model field. The simplest way is to use **the logged in user** that made the request. To do this, add the ``FieldHistoryMiddleware`` class to your ``MIDDLEWARE`` setting. 177 | 178 | .. code-block:: python 179 | 180 | MIDDLEWARE = [ 181 | 'django.contrib.sessions.middleware.SessionMiddleware', 182 | 'django.middleware.common.CommonMiddleware', 183 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 184 | 'field_history.middleware.FieldHistoryMiddleware', 185 | ] 186 | 187 | Alternatively, you can add a ``_field_history_user`` property to the model that has fields you are tracking. This property should return the user you would like stored on ``FieldHistory`` when your field is updated. 188 | 189 | .. code-block:: python 190 | 191 | class Pizza(models.Model): 192 | name = models.CharField(max_length=255) 193 | updated_by = models.ForeignKey('auth.User') 194 | 195 | field_history = FieldHistoryTracker(['name']) 196 | 197 | @property 198 | def _field_history_user(self): 199 | return self.updated_by 200 | 201 | Working with MySQL 202 | ------------------ 203 | 204 | If you're using MySQL, the default configuration will throw an exception when you run migrations. (By default, ``FieldHistory.object_id`` is implemented as a ``TextField`` for flexibility, but indexed columns in MySQL InnoDB tables may be a maximum of 767 bytes.) To fix this, you can set ``FIELD_HISTORY_OBJECT_ID_TYPE`` in settings.py to override the default field type with one that meets MySQL's constraints. ``FIELD_HISTORY_OBJECT_ID_TYPE`` may be set to either: 205 | 206 | 1. the Django model field class you wish to use, or 207 | 2. a tuple ``(field_class, kwargs)``, where ``field_class`` is a Django model field class and ``kwargs`` is a dict of arguments to pass to the field class constructor. 208 | 209 | To approximate the default behavior for Postgres when using MySQL, configure ``object_id`` to use a ``CharField`` by adding the following to settings.py: 210 | 211 | .. code-block:: python 212 | 213 | from django.db import models 214 | FIELD_HISTORY_OBJECT_ID_TYPE = (models.CharField, {'max_length': 100}) 215 | 216 | ``FIELD_HISTORY_OBJECT_ID_TYPE`` also allows you to use a field type that's more efficient for your use case, even if you're using Postgres (or a similarly unconstrained database). For example, if you always let Django auto-create an ``id`` field (implemented internally as an ``AutoField``), setting ``FIELD_HISTORY_OBJECT_ID_TYPE`` to ``IntegerField`` will result in efficiency gains (both in time and space). This would look like: 217 | 218 | .. code-block:: python 219 | 220 | from django.db import models 221 | FIELD_HISTORY_OBJECT_ID_TYPE = models.IntegerField 222 | 223 | Running Tests 224 | ------------- 225 | 226 | Does the code actually work? 227 | 228 | :: 229 | 230 | source /bin/activate 231 | (myenv) $ pip install -r requirements-test.txt 232 | (myenv) $ python runtests.py 233 | -------------------------------------------------------------------------------- /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 field_history 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-field-history' 50 | copyright = u'2016, Grant McConnaughey' 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 = field_history.__version__ 58 | # The full version, including alpha/beta/rc tags. 59 | release = field_history.__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 = 'default' 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 = ['_static'] 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-field-historydoc' 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-field-history.tex', u'django-field-history Documentation', 196 | u'Grant McConnaughey', '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-field-history', u'django-field-history Documentation', 226 | [u'Grant McConnaughey'], 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-field-history', u'django-field-history Documentation', 240 | u'Grant McConnaughey', 'django-field-history', '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-field-history'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 | At the command line:: 6 | 7 | $ easy_install django-field-history 8 | 9 | Or, if you have virtualenvwrapper installed:: 10 | 11 | $ mkvirtualenv django-field-history 12 | $ pip install django-field-history 13 | -------------------------------------------------------------------------------- /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 | To use django-field-history in a project:: 6 | 7 | import field_history 8 | -------------------------------------------------------------------------------- /field_history/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = '0.8.0' 2 | -------------------------------------------------------------------------------- /field_history/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | from .models import FieldHistory 4 | 5 | admin.site.register(FieldHistory) 6 | -------------------------------------------------------------------------------- /field_history/json_nested_serializer.py: -------------------------------------------------------------------------------- 1 | """ 2 | Serialize data to/from JSON 3 | Only one change comparing to Django build-in json serializer: obj.local_fields -> obj.fields for supporting 4 | nested models, parent fields are included to output 5 | """ 6 | 7 | # Avoid shadowing the standard library json module 8 | from __future__ import absolute_import 9 | from __future__ import unicode_literals 10 | 11 | import warnings 12 | 13 | from django.core.serializers.json import Serializer as JsonSerializer 14 | try: 15 | from django.utils import six 16 | except ImportError: 17 | import six 18 | 19 | try: 20 | from django.utils.deprecation import RemovedInDjango19Warning 21 | except ImportError: 22 | RemovedInDjango19Warning = None 23 | 24 | 25 | class Serializer(JsonSerializer): 26 | """ 27 | Convert a queryset to JSON. 28 | """ 29 | def serialize(self, queryset, **options): 30 | """ 31 | Serialize a queryset. 32 | """ 33 | self.options = options 34 | 35 | self.stream = options.pop("stream", six.StringIO()) 36 | self.selected_fields = options.pop("fields", None) 37 | self.use_natural_keys = options.pop("use_natural_keys", False) 38 | if self.use_natural_keys and RemovedInDjango19Warning is not None: 39 | warnings.warn("``use_natural_keys`` is deprecated; use ``use_natural_foreign_keys`` instead.", 40 | RemovedInDjango19Warning) 41 | self.use_natural_foreign_keys = options.pop('use_natural_foreign_keys', False) or self.use_natural_keys 42 | self.use_natural_primary_keys = options.pop('use_natural_primary_keys', False) 43 | 44 | self.start_serialization() 45 | self.first = True 46 | for obj in queryset: 47 | self.start_object(obj) 48 | # Use the concrete parent class' _meta instead of the object's _meta 49 | # This is to avoid local_fields problems for proxy models. Refs #17717. 50 | concrete_model = obj._meta.concrete_model 51 | # only one change local_fields -> fields for supporting nested models 52 | for field in concrete_model._meta.fields: 53 | if field.serialize: 54 | if field.remote_field is None: 55 | if self.selected_fields is None or field.attname in self.selected_fields: 56 | self.handle_field(obj, field) 57 | else: 58 | if self.selected_fields is None or field.attname[:-3] in self.selected_fields: 59 | self.handle_fk_field(obj, field) 60 | for field in concrete_model._meta.many_to_many: 61 | if field.serialize: 62 | if self.selected_fields is None or field.attname in self.selected_fields: 63 | self.handle_m2m_field(obj, field) 64 | self.end_object(obj) 65 | if self.first: 66 | self.first = False 67 | self.end_serialization() 68 | return self.getvalue() 69 | -------------------------------------------------------------------------------- /field_history/management/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/grantmcconnaughey/django-field-history/84cda9d5d49d5ea6220ab1c82878c37280490a6b/field_history/management/__init__.py -------------------------------------------------------------------------------- /field_history/management/commands/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/grantmcconnaughey/django-field-history/84cda9d5d49d5ea6220ab1c82878c37280490a6b/field_history/management/commands/__init__.py -------------------------------------------------------------------------------- /field_history/management/commands/createinitialfieldhistory.py: -------------------------------------------------------------------------------- 1 | import inspect 2 | 3 | from django.contrib.contenttypes.models import ContentType 4 | from django.apps import apps 5 | from django.core import serializers 6 | from django.core.management import BaseCommand 7 | 8 | from field_history.models import FieldHistory 9 | from field_history.tracker import FieldHistoryTracker, get_serializer_name 10 | 11 | 12 | class Command(BaseCommand): 13 | 14 | help = "Adds initial FieldHistory objects" 15 | 16 | def handle(self, *args, **options): 17 | models = [] 18 | for model in apps.get_models(): 19 | for member in inspect.getmembers(model): 20 | if isinstance(member[1], FieldHistoryTracker): 21 | models.append((model, member[1].fields)) 22 | break 23 | 24 | if models: 25 | self.stdout.write('Creating initial field history for {} models\n'.format(len(models))) 26 | 27 | for model_fields in models: 28 | model = model_fields[0] 29 | fields = model_fields[1] 30 | 31 | for obj in model._default_manager.all(): 32 | for field in list(fields): 33 | content_type = ContentType.objects.get_for_model(obj) 34 | if not FieldHistory.objects.filter( 35 | object_id=obj.pk, 36 | content_type=content_type, 37 | field_name=field).exists(): 38 | data = serializers.serialize(get_serializer_name(), 39 | [obj], 40 | fields=[field]) 41 | FieldHistory.objects.create( 42 | object=obj, 43 | field_name=field, 44 | serialized_data=data, 45 | ) 46 | else: 47 | self.stdout.write('There are no models to create field history for.') 48 | -------------------------------------------------------------------------------- /field_history/management/commands/renamefieldhistory.py: -------------------------------------------------------------------------------- 1 | from django.apps import apps 2 | from django.contrib.contenttypes.models import ContentType 3 | from django.core.management import BaseCommand, CommandError 4 | 5 | from field_history.models import FieldHistory 6 | 7 | 8 | class Command(BaseCommand): 9 | 10 | help = """Updates FieldHistory field_names for a given model. Run this after renaming a model field via migrations. 11 | 12 | Example: 13 | 14 | python manage.py renamefieldhistory --model=myapp.User --from_field=username to_field=handle 15 | """ 16 | 17 | def add_arguments(self, parser): 18 | parser.add_argument( 19 | '--model', 20 | type=str, 21 | help='The model class to update in ' 22 | 'app_label.model_name format (e.g. auth.User)') 23 | 24 | parser.add_argument( 25 | '--from_field', 26 | type=str, 27 | help='The old model field name') 28 | 29 | parser.add_argument( 30 | '--to_field', 31 | type=str, 32 | help='The new model field name') 33 | 34 | def handle(self, *args, **options): 35 | model_name = options.get('model') 36 | from_field = options.get('from_field') 37 | to_field = options.get('to_field') 38 | 39 | if not model_name: 40 | raise CommandError('--model_name is a required argument') 41 | if not from_field: 42 | raise CommandError('--from_field is a required argument') 43 | if not to_field: 44 | raise CommandError('--to_field is a required argument') 45 | 46 | model = apps.get_model(model_name) 47 | content_type = ContentType.objects.get_for_model(model) 48 | field_histories = FieldHistory.objects.filter(content_type=content_type, field_name=from_field) 49 | 50 | self.stdout.write('Updating {} FieldHistory object(s)\n'.format(field_histories.count())) 51 | 52 | field_histories.update(field_name=to_field) 53 | -------------------------------------------------------------------------------- /field_history/managers.py: -------------------------------------------------------------------------------- 1 | from django.db.models import Manager 2 | from django.contrib.contenttypes.models import ContentType 3 | 4 | 5 | class FieldHistoryManager(Manager): 6 | 7 | def get_for_model(self, object): 8 | content_type = ContentType.objects.get_for_model(object) 9 | return self.filter(object_id=object.pk, 10 | content_type=content_type) 11 | 12 | def get_for_model_and_field(self, object, field): 13 | return self.get_for_model(object).filter(field_name=field) 14 | -------------------------------------------------------------------------------- /field_history/middleware.py: -------------------------------------------------------------------------------- 1 | from django.utils.deprecation import MiddlewareMixin 2 | 3 | from .tracker import FieldHistoryTracker 4 | 5 | 6 | class FieldHistoryMiddleware(MiddlewareMixin): 7 | 8 | def process_request(self, request): 9 | FieldHistoryTracker.thread.request = request 10 | -------------------------------------------------------------------------------- /field_history/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by Django 1.9.2 on 2016-02-16 17:57 3 | from __future__ import unicode_literals 4 | 5 | from django.conf import settings 6 | from django.db import migrations, models 7 | import django.db.models.deletion 8 | 9 | from field_history.models import OBJECT_ID_TYPE_SETTING, instantiate_object_id_field 10 | 11 | 12 | class Migration(migrations.Migration): 13 | 14 | initial = True 15 | 16 | dependencies = [ 17 | ('contenttypes', '0001_initial'), 18 | migrations.swappable_dependency(settings.AUTH_USER_MODEL), 19 | ] 20 | 21 | operations = [ 22 | migrations.CreateModel( 23 | name='FieldHistory', 24 | fields=[ 25 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 26 | ('object_id', instantiate_object_id_field(getattr(settings, OBJECT_ID_TYPE_SETTING, models.TextField))), 27 | ('field_name', models.CharField(max_length=500)), 28 | ('serialized_data', models.TextField()), 29 | ('date_created', models.DateTimeField(auto_now_add=True, db_index=True)), 30 | ('content_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType')), 31 | ('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), 32 | ], 33 | ), 34 | ] 35 | -------------------------------------------------------------------------------- /field_history/migrations/0002_auto_20160413_1824.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.db import models, migrations 5 | 6 | 7 | class Migration(migrations.Migration): 8 | 9 | dependencies = [ 10 | ('field_history', '0001_initial'), 11 | ] 12 | 13 | operations = [ 14 | migrations.AlterModelOptions( 15 | name='fieldhistory', 16 | options={'get_latest_by': 'date_created'}, 17 | ), 18 | migrations.AlterField( 19 | model_name='fieldhistory', 20 | name='field_name', 21 | field=models.CharField(max_length=500, db_index=True), 22 | preserve_default=True, 23 | ), 24 | ] 25 | -------------------------------------------------------------------------------- /field_history/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/grantmcconnaughey/django-field-history/84cda9d5d49d5ea6220ab1c82878c37280490a6b/field_history/migrations/__init__.py -------------------------------------------------------------------------------- /field_history/models.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from django.conf import settings 3 | from django.contrib.contenttypes.fields import GenericForeignKey 4 | from django.core import serializers 5 | from django.db import models 6 | 7 | from .managers import FieldHistoryManager 8 | 9 | OBJECT_ID_TYPE_SETTING = 'FIELD_HISTORY_OBJECT_ID_TYPE' 10 | 11 | 12 | def instantiate_object_id_field(object_id_class_or_tuple=models.TextField): 13 | """ 14 | Instantiates and returns a model field for FieldHistory.object_id. 15 | 16 | object_id_class_or_tuple may be either a Django model field class or a 17 | tuple of (model_field, kwargs), where kwargs is a dict passed to 18 | model_field's constructor. 19 | """ 20 | if isinstance(object_id_class_or_tuple, (list, tuple)): 21 | object_id_class, object_id_kwargs = object_id_class_or_tuple 22 | else: 23 | object_id_class = object_id_class_or_tuple 24 | object_id_kwargs = {} 25 | 26 | if not issubclass(object_id_class, models.fields.Field): 27 | raise TypeError('settings.%s must be a Django model field or (field, kwargs) tuple' % OBJECT_ID_TYPE_SETTING) 28 | if not isinstance(object_id_kwargs, dict): 29 | raise TypeError('settings.%s kwargs must be a dict' % OBJECT_ID_TYPE_SETTING) 30 | 31 | return object_id_class(db_index=True, **object_id_kwargs) 32 | 33 | 34 | class FieldHistory(models.Model): 35 | object_id = instantiate_object_id_field(getattr(settings, OBJECT_ID_TYPE_SETTING, models.TextField)) 36 | content_type = models.ForeignKey('contenttypes.ContentType', db_index=True, on_delete=models.CASCADE) 37 | object = GenericForeignKey() 38 | field_name = models.CharField(max_length=500, db_index=True) 39 | serialized_data = models.TextField() 40 | date_created = models.DateTimeField(auto_now_add=True, db_index=True) 41 | user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.CASCADE) 42 | 43 | objects = FieldHistoryManager() 44 | 45 | class Meta: 46 | app_label = 'field_history' 47 | get_latest_by = 'date_created' 48 | 49 | def __str__(self): 50 | return u'{} field history for {}'.format(self.field_name, self.object) 51 | 52 | @property 53 | def field_value(self): 54 | instances = serializers.deserialize('json', self.serialized_data) 55 | instance = list(instances)[0].object 56 | return getattr(instance, self.field_name) 57 | -------------------------------------------------------------------------------- /field_history/tracker.py: -------------------------------------------------------------------------------- 1 | from __future__ import unicode_literals 2 | 3 | from copy import deepcopy 4 | import threading 5 | 6 | from django.core import serializers 7 | from django.conf import settings 8 | from django.db import models 9 | 10 | from .models import FieldHistory 11 | 12 | 13 | def get_serializer_name(): 14 | return getattr(settings, 'FIELD_HISTORY_SERIALIZER_NAME', 'json') 15 | 16 | 17 | def curry(*args, **kwargs): 18 | try: 19 | # Python 3.4+ 20 | from functools import partialmethod 21 | return partialmethod(*args, **kwargs) 22 | except ImportError: 23 | # Python 2.7 24 | from django.utils.functional import curry 25 | return curry(*args, **kwargs) 26 | 27 | 28 | class FieldInstanceTracker(object): 29 | def __init__(self, instance, fields): 30 | self.instance = instance 31 | self.fields = fields 32 | 33 | def get_field_value(self, field): 34 | return getattr(self.instance, field) 35 | 36 | def set_saved_fields(self, fields=None): 37 | if not self.instance.pk: 38 | self.saved_data = {} 39 | elif not fields: 40 | self.saved_data = self.current() 41 | 42 | # preventing mutable fields side effects 43 | for field, field_value in self.saved_data.items(): 44 | self.saved_data[field] = deepcopy(field_value) 45 | 46 | def current(self, fields=None): 47 | """Returns dict of current values for all tracked fields""" 48 | if fields is None: 49 | fields = self.fields 50 | 51 | return dict((f, self.get_field_value(f)) for f in fields) 52 | 53 | def has_changed(self, field): 54 | """Returns ``True`` if field has changed from currently saved value""" 55 | return self.previous(field) != self.get_field_value(field) 56 | 57 | def previous(self, field): 58 | """Returns currently saved value of given field""" 59 | return self.saved_data.get(field) 60 | 61 | 62 | class FieldHistoryTracker(object): 63 | 64 | tracker_class = FieldInstanceTracker 65 | thread = threading.local() 66 | 67 | def __init__(self, fields): 68 | if not fields: 69 | raise ValueError("Can't track zero fields") 70 | self.fields = set(fields) 71 | 72 | def contribute_to_class(self, cls, name): 73 | setattr(cls, '_get_field_history', _get_field_history) 74 | for field in self.fields: 75 | setattr(cls, 'get_%s_history' % field, 76 | curry(cls._get_field_history, field=field)) 77 | self.name = name 78 | self.attname = '_%s' % name 79 | models.signals.class_prepared.connect(self.finalize_class, sender=cls) 80 | 81 | def finalize_class(self, sender, **kwargs): 82 | self.fields = self.fields 83 | models.signals.post_init.connect(self.initialize_tracker) 84 | self.model_class = sender 85 | setattr(sender, self.name, self) 86 | 87 | def initialize_tracker(self, sender, instance, **kwargs): 88 | if not isinstance(instance, self.model_class): 89 | return # Only init instances of given model (including children) 90 | self._initialize_tracker(instance) 91 | self.patch_save(instance) 92 | 93 | def _initialize_tracker(self, instance): 94 | tracker = self.tracker_class(instance, self.fields) 95 | setattr(instance, self.attname, tracker) 96 | tracker.set_saved_fields() 97 | 98 | def patch_save(self, instance): 99 | original_save = instance.save 100 | 101 | def save(**kwargs): 102 | is_new_object = instance.pk is None 103 | ret = original_save(**kwargs) 104 | tracker = getattr(instance, self.attname) 105 | field_histories = [] 106 | 107 | # Create a FieldHistory for all self.fields that have changed 108 | for field in self.fields: 109 | if tracker.has_changed(field) or is_new_object: 110 | data = serializers.serialize(get_serializer_name(), 111 | [instance], 112 | fields=[field]) 113 | user = self.get_field_history_user(instance) 114 | history = FieldHistory( 115 | object=instance, 116 | field_name=field, 117 | serialized_data=data, 118 | user=user, 119 | ) 120 | field_histories.append(history) 121 | 122 | if field_histories: 123 | # Create all the FieldHistory objects in one batch 124 | FieldHistory.objects.bulk_create(field_histories) 125 | 126 | # Update tracker in case this model is saved again 127 | self._initialize_tracker(instance) 128 | 129 | return ret 130 | instance.save = save 131 | 132 | def get_field_history_user(self, instance): 133 | try: 134 | return instance._field_history_user 135 | except AttributeError: 136 | try: 137 | if self.thread.request.user.is_authenticated: 138 | return self.thread.request.user 139 | return None 140 | except AttributeError: 141 | return None 142 | 143 | def __get__(self, instance, owner): 144 | if instance is None: 145 | return self 146 | else: 147 | return FieldHistory.objects.get_for_model(instance) 148 | 149 | 150 | def _get_field_history(self, field): 151 | return FieldHistory.objects.get_for_model_and_field(self, field) 152 | -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | try: 6 | from django.conf import settings 7 | 8 | settings.configure( 9 | DEBUG=True, 10 | USE_TZ=True, 11 | DATABASES={ 12 | "default": { 13 | "ENGINE": "django.db.backends.sqlite3", 14 | "NAME": "db.sqlite3" 15 | } 16 | }, 17 | ROOT_URLCONF="tests.urls", 18 | INSTALLED_APPS=[ 19 | "django.contrib.admin", 20 | "django.contrib.auth", 21 | "django.contrib.contenttypes", 22 | "django.contrib.messages", 23 | "django.contrib.sites", 24 | "field_history", 25 | "tests", 26 | ], 27 | SITE_ID=1, 28 | MIDDLEWARE=( 29 | 'django.contrib.sessions.middleware.SessionMiddleware', 30 | 'django.middleware.common.CommonMiddleware', 31 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 32 | 'django.contrib.messages.middleware.MessageMiddleware', 33 | 'field_history.middleware.FieldHistoryMiddleware', 34 | ), 35 | TEMPLATES=[ 36 | { 37 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 38 | 'OPTIONS': { 39 | 'context_processors': [ 40 | 'django.contrib.auth.context_processors.auth', 41 | 'django.contrib.messages.context_processors.messages' 42 | ] 43 | } 44 | } 45 | ] 46 | ) 47 | 48 | try: 49 | import django 50 | setup = django.setup 51 | except AttributeError: 52 | pass 53 | else: 54 | setup() 55 | 56 | except ImportError: 57 | import traceback 58 | traceback.print_exc() 59 | raise ImportError("To fix this error, run: pip install -r requirements-test.txt") 60 | 61 | 62 | if __name__ == "__main__": 63 | sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) 64 | 65 | from django.core.management import execute_from_command_line 66 | 67 | execute_from_command_line(sys.argv) 68 | -------------------------------------------------------------------------------- /requirements-test.txt: -------------------------------------------------------------------------------- 1 | coverage 2 | mock 3 | flake8 4 | -------------------------------------------------------------------------------- /requirements_dev.txt: -------------------------------------------------------------------------------- 1 | bumpversion==0.5.3 2 | twine 3 | wheel 4 | -------------------------------------------------------------------------------- /runtests.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | try: 4 | from django.conf import settings 5 | from django.test.utils import get_runner 6 | 7 | settings.configure( 8 | DEBUG=True, 9 | USE_TZ=True, 10 | DATABASES={ 11 | "default": { 12 | "ENGINE": "django.db.backends.sqlite3", 13 | } 14 | }, 15 | ROOT_URLCONF="tests.urls", 16 | INSTALLED_APPS=[ 17 | "django.contrib.admin", 18 | "django.contrib.auth", 19 | "django.contrib.contenttypes", 20 | "django.contrib.messages", 21 | "django.contrib.sessions", 22 | "django.contrib.sites", 23 | "field_history", 24 | "tests", 25 | ], 26 | SITE_ID=1, 27 | MIDDLEWARE=( 28 | 'django.contrib.sessions.middleware.SessionMiddleware', 29 | 'django.middleware.common.CommonMiddleware', 30 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 31 | 'django.contrib.messages.middleware.MessageMiddleware', 32 | 'field_history.middleware.FieldHistoryMiddleware', 33 | ), 34 | TEMPLATES=[ 35 | { 36 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 37 | 'OPTIONS': { 38 | 'context_processors': [ 39 | 'django.contrib.auth.context_processors.auth', 40 | 'django.contrib.messages.context_processors.messages' 41 | ] 42 | } 43 | } 44 | ] 45 | ) 46 | 47 | try: 48 | import django 49 | setup = django.setup 50 | except AttributeError: 51 | pass 52 | else: 53 | setup() 54 | 55 | except ImportError: 56 | import traceback 57 | traceback.print_exc() 58 | raise ImportError("To fix this error, run: pip install -r requirements-test.txt") 59 | 60 | 61 | def run_tests(*test_args): 62 | if not test_args: 63 | test_args = ['tests'] 64 | 65 | # Run tests 66 | TestRunner = get_runner(settings) 67 | test_runner = TestRunner() 68 | 69 | failures = test_runner.run_tests(test_args) 70 | 71 | if failures: 72 | sys.exit(bool(failures)) 73 | 74 | 75 | if __name__ == '__main__': 76 | run_tests(*sys.argv[1:]) 77 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [wheel] 2 | universal = 1 3 | 4 | [flake8] 5 | ignore = 6 | E501, # Line too long 7 | exclude = 8 | docs/*, 9 | setup.py, 10 | max-complexity = 12 -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | import os 4 | import re 5 | import sys 6 | 7 | try: 8 | from setuptools import setup 9 | except ImportError: 10 | from distutils.core import setup 11 | 12 | 13 | def get_version(*file_paths): 14 | filename = os.path.join(os.path.dirname(__file__), *file_paths) 15 | version_file = open(filename).read() 16 | version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", 17 | version_file, re.M) 18 | if version_match: 19 | return version_match.group(1) 20 | raise RuntimeError('Unable to find version string.') 21 | 22 | version = get_version('field_history', '__init__.py') 23 | 24 | if sys.argv[-1] == 'publish': 25 | try: 26 | import wheel 27 | except ImportError: 28 | print('Wheel library missing. Please run "pip install wheel"') 29 | sys.exit() 30 | os.system('python setup.py sdist upload') 31 | os.system('python setup.py bdist_wheel upload') 32 | sys.exit() 33 | 34 | if sys.argv[-1] == 'tag': 35 | print("Tagging the version on github:") 36 | os.system("git tag -a %s -m 'version %s'" % (version, version)) 37 | os.system("git push --tags") 38 | sys.exit() 39 | 40 | readme = open('README.rst').read() 41 | history = open('HISTORY.rst').read().replace('.. :changelog:', '') 42 | 43 | setup( 44 | name='django-field-history', 45 | version=version, 46 | description="""A Django app to track changes to a model field.""", 47 | long_description=readme + '\n\n' + history, 48 | author='Grant McConnaughey', 49 | author_email='grantmcconnaughey@gmail.com', 50 | url='https://github.com/grantmcconnaughey/django-field-history', 51 | packages=[ 52 | 'field_history', 53 | ], 54 | include_package_data=True, 55 | install_requires=[ 56 | ], 57 | license="BSD", 58 | zip_safe=False, 59 | keywords='django-field-history', 60 | classifiers=[ 61 | 'Development Status :: 4 - Beta', 62 | 'Framework :: Django', 63 | 'Framework :: Django :: 1.11', 64 | 'Framework :: Django :: 2.0', 65 | 'Framework :: Django :: 2.1', 66 | 'Framework :: Django :: 2.2', 67 | 'Framework :: Django :: 3.0', 68 | 'Intended Audience :: Developers', 69 | 'License :: OSI Approved :: BSD License', 70 | 'Natural Language :: English', 71 | 'Programming Language :: Python :: 2', 72 | 'Programming Language :: Python :: 2.7', 73 | 'Programming Language :: Python :: 3', 74 | 'Programming Language :: Python :: 3.4', 75 | 'Programming Language :: Python :: 3.5', 76 | 'Programming Language :: Python :: 3.6', 77 | 'Programming Language :: Python :: 3.7', 78 | 'Programming Language :: Python :: 3.8', 79 | ], 80 | ) 81 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/grantmcconnaughey/django-field-history/84cda9d5d49d5ea6220ab1c82878c37280490a6b/tests/__init__.py -------------------------------------------------------------------------------- /tests/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.2.9 on 2020-01-04 21:20 2 | 3 | from django.conf import settings 4 | from django.db import migrations, models 5 | import django.db.models.deletion 6 | 7 | 8 | class Migration(migrations.Migration): 9 | 10 | initial = True 11 | 12 | dependencies = [ 13 | migrations.swappable_dependency(settings.AUTH_USER_MODEL), 14 | ] 15 | 16 | operations = [ 17 | migrations.CreateModel( 18 | name='Human', 19 | fields=[ 20 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 21 | ('age', models.IntegerField(blank=True, null=True)), 22 | ('is_female', models.BooleanField(default=True)), 23 | ('body_temp', models.DecimalField(blank=True, decimal_places=2, max_digits=15, null=True)), 24 | ('birth_date', models.DateField(blank=True, null=True)), 25 | ], 26 | ), 27 | migrations.CreateModel( 28 | name='Person', 29 | fields=[ 30 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 31 | ('name', models.CharField(max_length=255)), 32 | ('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), 33 | ], 34 | ), 35 | migrations.CreateModel( 36 | name='Pet', 37 | fields=[ 38 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 39 | ('name', models.CharField(max_length=255)), 40 | ], 41 | ), 42 | migrations.CreateModel( 43 | name='PizzaOrder', 44 | fields=[ 45 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 46 | ('status', models.CharField(choices=[('ORDERED', 'Ordered'), ('COOKING', 'Cooking'), ('COMPLETE', 'Complete')], max_length=64)), 47 | ], 48 | ), 49 | migrations.CreateModel( 50 | name='Owner', 51 | fields=[ 52 | ('person_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='tests.Person')), 53 | ('pet', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='tests.Pet')), 54 | ], 55 | bases=('tests.person',), 56 | ), 57 | ] 58 | -------------------------------------------------------------------------------- /tests/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/grantmcconnaughey/django-field-history/84cda9d5d49d5ea6220ab1c82878c37280490a6b/tests/migrations/__init__.py -------------------------------------------------------------------------------- /tests/models.py: -------------------------------------------------------------------------------- 1 | from django.conf import settings 2 | from django.db import models 3 | 4 | from field_history.tracker import FieldHistoryTracker 5 | 6 | 7 | class Pet(models.Model): 8 | name = models.CharField(max_length=255) 9 | 10 | 11 | class Person(models.Model): 12 | name = models.CharField(max_length=255) 13 | created_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.CASCADE) 14 | 15 | field_history = FieldHistoryTracker(['name']) 16 | 17 | @property 18 | def _field_history_user(self): 19 | return self.created_by 20 | 21 | 22 | class Owner(Person): 23 | pet = models.ForeignKey(Pet, blank=True, null=True, on_delete=models.CASCADE) 24 | 25 | field_history = FieldHistoryTracker(['name', 'pet']) 26 | 27 | 28 | class Human(models.Model): 29 | age = models.IntegerField(blank=True, null=True) 30 | is_female = models.BooleanField(default=True) 31 | body_temp = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) 32 | birth_date = models.DateField(blank=True, null=True) 33 | 34 | field_history = FieldHistoryTracker(['age', 'is_female', 35 | 'body_temp', 'birth_date']) 36 | 37 | 38 | class PizzaOrder(models.Model): 39 | STATUS_ORDERED = 'ORDERED' 40 | STATUS_COOKING = 'COOKING' 41 | STATUS_COMPLETE = 'COMPLETE' 42 | 43 | STATUS_CHOICES = ( 44 | (STATUS_ORDERED, 'Ordered'), 45 | (STATUS_COOKING, 'Cooking'), 46 | (STATUS_COMPLETE, 'Complete'), 47 | ) 48 | status = models.CharField(max_length=64, choices=STATUS_CHOICES) 49 | 50 | field_history = FieldHistoryTracker(['status']) 51 | -------------------------------------------------------------------------------- /tests/tests.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | import datetime 4 | from decimal import Decimal 5 | 6 | from django.contrib.auth import get_user_model 7 | from django.core.management import CommandError, call_command 8 | from django.urls import reverse 9 | from django.db import models 10 | from django.test.utils import override_settings 11 | from django.test import TestCase 12 | try: 13 | from django.utils import six 14 | except ImportError: 15 | import six 16 | from field_history.models import FieldHistory, instantiate_object_id_field 17 | from field_history.tracker import FieldHistoryTracker 18 | 19 | from .models import Human, Owner, Person, Pet, PizzaOrder 20 | 21 | JSON_NESTED_SETTINGS = dict(FIELD_HISTORY_SERIALIZER_NAME='json_nested', 22 | SERIALIZATION_MODULES={'json_nested': 'field_history.json_nested_serializer'}) 23 | 24 | 25 | class FieldHistoryTests(TestCase): 26 | 27 | def test_readme(self): 28 | """Update this test when changes are made to the README.rst example.""" 29 | # No FieldHistory objects yet 30 | assert FieldHistory.objects.count() == 0 31 | 32 | # Creating an object will make one 33 | pizza_order = PizzaOrder.objects.create(status='ORDERED') 34 | assert FieldHistory.objects.count() == 1 35 | 36 | # This object has some fields on it 37 | history = FieldHistory.objects.get() 38 | assert history.object == pizza_order 39 | assert history.field_name == 'status' 40 | assert history.field_value == 'ORDERED' 41 | assert history.date_created is not None 42 | 43 | # You can query FieldHistory using the get_{field_name}_history() 44 | # method added to your model 45 | histories = pizza_order.get_status_history() 46 | assert list(FieldHistory.objects.all()) == list(histories) 47 | 48 | # Or using the custom FieldHistory manager 49 | histories2 = FieldHistory.objects.get_for_model_and_field(pizza_order, 'status') 50 | assert list(histories) == list(histories2) 51 | 52 | # Updating that particular field creates a new FieldHistory 53 | pizza_order.status = 'COOKING' 54 | pizza_order.save() 55 | assert FieldHistory.objects.count() == 2 56 | 57 | updated_history = histories.latest() 58 | assert updated_history.object == pizza_order 59 | assert updated_history.field_name == 'status' 60 | assert updated_history.field_value == 'COOKING' 61 | assert updated_history.date_created is not None 62 | 63 | def test_str(self): 64 | person = Person.objects.create(name='Initial Name') 65 | 66 | history = FieldHistory.objects.get() 67 | 68 | self.assertEqual(str(history), 69 | 'name field history for {}'.format(str(person))) 70 | 71 | def test_new_object_creates_field_history(self): 72 | # No FieldHistory objects yet 73 | self.assertEqual(FieldHistory.objects.count(), 0) 74 | 75 | person = Person.objects.create(name='Initial Name') 76 | 77 | # Creating an object will make one 78 | self.assertEqual(FieldHistory.objects.count(), 1) 79 | 80 | # This object has some fields on it 81 | history = FieldHistory.objects.get() 82 | self.assertEqual(history.object, person) 83 | self.assertEqual(history.field_name, 'name') 84 | self.assertEqual(history.field_value, 'Initial Name') 85 | self.assertIsNotNone(history.date_created) 86 | self.assertIsNone(history.user) 87 | 88 | def test_field_history_user_is_from_field_history_user_property(self): 89 | user = get_user_model().objects.create( 90 | username='test', 91 | email='test@test.com') 92 | person = Person.objects.create( 93 | name='Initial Name', 94 | created_by=user) 95 | 96 | history = person.get_name_history().get() 97 | self.assertEqual(history.object, person) 98 | self.assertEqual(history.field_name, 'name') 99 | self.assertEqual(history.field_value, 'Initial Name') 100 | self.assertIsNotNone(history.date_created) 101 | self.assertEqual(history.user, user) 102 | 103 | def test_field_history_user_is_from_request_user(self): 104 | user = get_user_model().objects.create( 105 | username='test', 106 | email='test@test.com') 107 | user.set_password('password') 108 | user.save() 109 | self.client.login(username='test', password='password') 110 | 111 | response = self.client.get(reverse("index")) 112 | 113 | # Make sure the view worked 114 | self.assertEqual(response.status_code, 200) 115 | order = PizzaOrder.objects.get() 116 | history = order.get_status_history().get() 117 | self.assertEqual(history.object, order) 118 | self.assertEqual(history.field_name, 'status') 119 | self.assertEqual(history.field_value, 'ORDERED') 120 | self.assertIsNotNone(history.date_created) 121 | self.assertEqual(history.user, user) 122 | 123 | # Don't pollute future tests 124 | FieldHistoryTracker.thread.request = None 125 | 126 | def test_updated_object_creates_additional_field_history(self): 127 | person = Person.objects.create(name='Initial Name') 128 | 129 | # Updating that particular field creates a new FieldHistory 130 | person.name = 'Updated Name' 131 | person.save() 132 | self.assertEqual(FieldHistory.objects.count(), 2) 133 | 134 | histories = FieldHistory.objects.get_for_model_and_field(person, 'name') 135 | 136 | updated_history = histories.order_by('-date_created').first() 137 | self.assertEqual(updated_history.object, person) 138 | self.assertEqual(updated_history.field_name, 'name') 139 | self.assertEqual(updated_history.field_value, 'Updated Name') 140 | self.assertIsNotNone(updated_history.date_created) 141 | 142 | # One more time for good measure 143 | person.name = 'Updated Again' 144 | person.save() 145 | self.assertEqual(FieldHistory.objects.count(), 3) 146 | 147 | histories = FieldHistory.objects.get_for_model_and_field(person, 'name') 148 | 149 | third_history = histories.order_by('-date_created').first() 150 | self.assertEqual(third_history.object, person) 151 | self.assertEqual(third_history.field_name, 'name') 152 | self.assertEqual(third_history.field_value, 'Updated Again') 153 | self.assertIsNotNone(third_history.date_created) 154 | 155 | def test_model_field_history_attribute_returns_all_histories(self): 156 | person = Person.objects.create(name='Initial Name') 157 | 158 | histories = FieldHistory.objects.get_for_model_and_field(person, 'name') 159 | 160 | six.assertCountEqual(self, list(person.field_history), list(histories)) 161 | 162 | def test_model_has_get_field_history_method(self): 163 | person = Person.objects.create(name='Initial Name') 164 | 165 | history = FieldHistory.objects.get() 166 | 167 | # Or using the {field_name}_history property added to your model 168 | six.assertCountEqual(self, list(person.get_name_history()), [history]) 169 | 170 | def test_field_history_is_not_created_if_field_value_did_not_change(self): 171 | person = Person.objects.create(name='Initial Name') 172 | 173 | self.assertEqual(FieldHistory.objects.count(), 1) 174 | 175 | # The value of person did not change, so don't create a new FieldHistory 176 | person.name = 'Initial Name' 177 | person.save() 178 | 179 | self.assertEqual(FieldHistory.objects.count(), 1) 180 | 181 | def test_field_history_works_with_integer_field(self): 182 | human = Human.objects.create(age=18) 183 | 184 | self.assertEqual(human.get_age_history().count(), 1) 185 | history = human.get_age_history()[0] 186 | 187 | self.assertEqual(history.object, human) 188 | self.assertEqual(history.field_name, 'age') 189 | self.assertEqual(history.field_value, 18) 190 | self.assertIsNotNone(history.date_created) 191 | 192 | def test_field_history_works_with_decimal_field(self): 193 | human = Human.objects.create(body_temp=Decimal(98.6)) 194 | 195 | self.assertEqual(human.get_body_temp_history().count(), 1) 196 | history = human.get_body_temp_history()[0] 197 | 198 | self.assertEqual(history.object, human) 199 | self.assertEqual(history.field_name, 'body_temp') 200 | self.assertEqual(history.field_value, Decimal(98.6)) 201 | self.assertIsNotNone(history.date_created) 202 | 203 | def test_field_history_works_with_boolean_field(self): 204 | human = Human.objects.create(is_female=True) 205 | 206 | self.assertEqual(human.get_is_female_history().count(), 1) 207 | history = human.get_is_female_history()[0] 208 | 209 | self.assertEqual(history.object, human) 210 | self.assertEqual(history.field_name, 'is_female') 211 | self.assertEqual(history.field_value, True) 212 | self.assertIsNotNone(history.date_created) 213 | 214 | def test_field_history_works_with_date_field(self): 215 | birth_date = datetime.date(1991, 11, 6) 216 | human = Human.objects.create(birth_date=birth_date) 217 | 218 | self.assertEqual(human.get_birth_date_history().count(), 1) 219 | history = human.get_birth_date_history()[0] 220 | 221 | self.assertEqual(history.object, human) 222 | self.assertEqual(history.field_name, 'birth_date') 223 | self.assertEqual(history.field_value, birth_date) 224 | self.assertIsNotNone(history.date_created) 225 | 226 | def test_field_history_tracks_multiple_fields_changed_at_same_time(self): 227 | human = Human.objects.create( 228 | birth_date=datetime.date(1991, 11, 6), 229 | is_female=True, 230 | body_temp=98.6, 231 | age=18, 232 | ) 233 | 234 | self.assertEqual(FieldHistory.objects.count(), 4) 235 | self.assertEqual(FieldHistory.objects.get_for_model_and_field(human, 'birth_date').count(), 1) 236 | self.assertEqual(FieldHistory.objects.get_for_model_and_field(human, 'is_female').count(), 1) 237 | self.assertEqual(FieldHistory.objects.get_for_model_and_field(human, 'body_temp').count(), 1) 238 | self.assertEqual(FieldHistory.objects.get_for_model_and_field(human, 'age').count(), 1) 239 | 240 | human.birth_date = datetime.date(1992, 11, 6) 241 | human.is_female = False 242 | human.body_temp = 100.0 243 | human.age = 21 244 | human.save() 245 | 246 | self.assertEqual(FieldHistory.objects.count(), 8) 247 | self.assertEqual(FieldHistory.objects.get_for_model_and_field(human, 'birth_date').count(), 2) 248 | self.assertEqual(FieldHistory.objects.get_for_model_and_field(human, 'is_female').count(), 2) 249 | self.assertEqual(FieldHistory.objects.get_for_model_and_field(human, 'body_temp').count(), 2) 250 | self.assertEqual(FieldHistory.objects.get_for_model_and_field(human, 'age').count(), 2) 251 | 252 | def test_field_history_works_with_foreign_key_field(self): 253 | pet = Pet.objects.create(name='Garfield') 254 | owner = Owner.objects.create(name='Jon', pet=pet) 255 | 256 | self.assertEqual(owner.get_pet_history().count(), 1) 257 | history = owner.get_pet_history()[0] 258 | 259 | self.assertEqual(history.object, owner) 260 | self.assertEqual(history.field_name, 'pet') 261 | self.assertEqual(history.field_value, pet) 262 | self.assertIsNotNone(history.date_created) 263 | 264 | def test_field_history_works_with_field_set_to_None(self): 265 | owner = Owner.objects.create(pet=None) 266 | 267 | history = owner.get_pet_history()[0] 268 | 269 | self.assertEqual(history.object, owner) 270 | self.assertEqual(history.field_name, 'pet') 271 | self.assertEqual(history.field_value, None) 272 | 273 | @override_settings(**JSON_NESTED_SETTINGS) 274 | def test_field_history_works_with_field_of_parent_model(self): 275 | owner = Owner.objects.create(name='Jon') 276 | 277 | history = owner.get_name_history()[0] 278 | 279 | self.assertEqual(history.object, owner) 280 | self.assertEqual(history.field_name, 'name') 281 | self.assertEqual(history.field_value, 'Jon') 282 | 283 | def test_object_id_field_type_class(self): 284 | field = instantiate_object_id_field(models.PositiveIntegerField) 285 | self.assertIsInstance(field, models.PositiveIntegerField) 286 | 287 | def test_object_id_field_type_tuple(self): 288 | field = instantiate_object_id_field((models.CharField, {'max_length': 20})) 289 | self.assertIsInstance(field, models.CharField) 290 | self.assertEqual(field.max_length, 20) 291 | 292 | def test_object_id_field_type_requires_field_class(self): 293 | self.assertRaises(TypeError, lambda: instantiate_object_id_field(int)) 294 | 295 | def test_object_id_field_type_requires_kwargs_as_dict(self): 296 | object_id_tuple_bad_kwargs = (models.TextField, 10) 297 | self.assertRaises(TypeError, lambda: instantiate_object_id_field(object_id_tuple_bad_kwargs)) 298 | 299 | 300 | class ManagementCommandsTests(TestCase): 301 | 302 | def test_createinitialfieldhistory_command_no_objects(self): 303 | call_command('createinitialfieldhistory') 304 | 305 | self.assertEqual(FieldHistory.objects.count(), 0) 306 | 307 | def test_createinitialfieldhistory_command_one_object(self): 308 | person = Person.objects.create(name='Initial Name') 309 | FieldHistory.objects.all().delete() 310 | 311 | call_command('createinitialfieldhistory') 312 | 313 | self.assertEqual(FieldHistory.objects.count(), 1) 314 | 315 | history = FieldHistory.objects.get() 316 | self.assertEqual(history.object, person) 317 | self.assertEqual(history.field_name, 'name') 318 | self.assertEqual(history.field_value, 'Initial Name') 319 | self.assertIsNotNone(history.date_created) 320 | 321 | def test_createinitialfieldhistory_command_only_tracks_new_object(self): 322 | Person.objects.create(name='Initial Name') 323 | FieldHistory.objects.all().delete() 324 | call_command('createinitialfieldhistory') 325 | 326 | self.assertEqual(FieldHistory.objects.count(), 1) 327 | 328 | PizzaOrder.objects.create(status=PizzaOrder.STATUS_ORDERED) 329 | call_command('createinitialfieldhistory') 330 | 331 | self.assertEqual(FieldHistory.objects.count(), 2) 332 | 333 | def test_renamefieldhistory(self): 334 | Person.objects.create(name='Initial Name') 335 | 336 | self.assertEqual(FieldHistory.objects.filter(field_name='name').count(), 1) 337 | 338 | call_command( 339 | 'renamefieldhistory', 340 | model='tests.Person', 341 | from_field='name', 342 | to_field='name2') 343 | 344 | self.assertEqual(FieldHistory.objects.filter(field_name='name').count(), 0) 345 | self.assertEqual(FieldHistory.objects.filter(field_name='name2').count(), 1) 346 | 347 | def test_renamefieldhistory_model_arg_is_required(self): 348 | Person.objects.create(name='Initial Name') 349 | 350 | self.assertEqual(FieldHistory.objects.filter(field_name='name').count(), 1) 351 | 352 | with self.assertRaises(CommandError): 353 | call_command('renamefieldhistory', from_field='name', to_field='name2') 354 | 355 | def test_renamefieldhistory_from_field_arg_is_required(self): 356 | Person.objects.create(name='Initial Name') 357 | 358 | self.assertEqual(FieldHistory.objects.filter(field_name='name').count(), 1) 359 | 360 | with self.assertRaises(CommandError): 361 | call_command('renamefieldhistory', model='tests.Person', to_field='name2') 362 | 363 | def test_renamefieldhistory_to_field_arg_is_required(self): 364 | Person.objects.create(name='Initial Name') 365 | 366 | self.assertEqual(FieldHistory.objects.filter(field_name='name').count(), 1) 367 | 368 | with self.assertRaises(CommandError): 369 | call_command('renamefieldhistory', model='tests.Person', from_field='name') 370 | -------------------------------------------------------------------------------- /tests/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import url 2 | from django.contrib import admin 3 | 4 | from . import views 5 | 6 | 7 | urlpatterns = [ 8 | url(r"^$", views.test_view, name="index"), 9 | url(r"^admin/", admin.site.urls), 10 | ] 11 | -------------------------------------------------------------------------------- /tests/views.py: -------------------------------------------------------------------------------- 1 | from django.contrib.auth.decorators import login_required 2 | from django.http.response import HttpResponse 3 | 4 | from .models import PizzaOrder 5 | 6 | 7 | @login_required 8 | def test_view(request): 9 | PizzaOrder.objects.create(status='ORDERED') 10 | return HttpResponse() 11 | --------------------------------------------------------------------------------