From f9af66adbd5afb7f05b317efc0df6a7d1c05af71 Mon Sep 17 00:00:00 2001 From: Oskar Hollmann Date: Mon, 13 Feb 2017 13:59:46 +0100 Subject: [PATCH] Documentation converted to reStructuredText, changed licence --- .gitignore | 1 + LICENSE | 167 +------------------- README.md | 335 +++------------------------------------ docs/Makefile | 192 ++++++++++++++++++++++ docs/conf.py | 358 ++++++++++++++++++++++++++++++++++++++++++ docs/dispatchers.rst | 89 +++++++++++ docs/forms.rst | 14 ++ docs/index.rst | 76 +++++++++ docs/installation.rst | 43 +++++ docs/make.bat | 263 +++++++++++++++++++++++++++++++ docs/models.rst | 100 ++++++++++++ docs/shortcuts.rst | 67 ++++++++ docs/utils.rst | 114 ++++++++++++++ 13 files changed, 1343 insertions(+), 476 deletions(-) create mode 100644 docs/Makefile create mode 100644 docs/conf.py create mode 100644 docs/dispatchers.rst create mode 100644 docs/forms.rst create mode 100644 docs/index.rst create mode 100644 docs/installation.rst create mode 100644 docs/make.bat create mode 100644 docs/models.rst create mode 100644 docs/shortcuts.rst create mode 100644 docs/utils.rst diff --git a/.gitignore b/.gitignore index 6420357..fbd069d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ # Documentation # ################# doc/ +.build # Compiled source # ################### diff --git a/LICENSE b/LICENSE index fb6d90b..923409f 100644 --- a/LICENSE +++ b/LICENSE @@ -1,166 +1,11 @@ -GNU LESSER GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 +Copyright 2017 Luboš Mátl, Lukáš Rychtecký, Oskar Hollmann - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - This version of the GNU Lesser General Public License incorporates -the terms and conditions of version 3 of the GNU General Public -License, supplemented by the additional permissions listed below. +2. 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. - 0. Additional Definitions. - - As used herein, "this License" refers to version 3 of the GNU Lesser -General Public License, and the "GNU GPL" refers to version 3 of the GNU -General Public License. - - "The Library" refers to a covered work governed by this License, -other than an Application or a Combined Work as defined below. - - An "Application" is any work that makes use of an interface provided -by the Library, but which is not otherwise based on the Library. -Defining a subclass of a class defined by the Library is deemed a mode -of using an interface provided by the Library. - - A "Combined Work" is a work produced by combining or linking an -Application with the Library. The particular version of the Library -with which the Combined Work was made is also called the "Linked -Version". - - The "Minimal Corresponding Source" for a Combined Work means the -Corresponding Source for the Combined Work, excluding any source code -for portions of the Combined Work that, considered in isolation, are -based on the Application, and not on the Linked Version. - - The "Corresponding Application Code" for a Combined Work means the -object code and/or source code for the Application, including any data -and utility programs needed for reproducing the Combined Work from the -Application, but excluding the System Libraries of the Combined Work. - - 1. Exception to Section 3 of the GNU GPL. - - You may convey a covered work under sections 3 and 4 of this License -without being bound by section 3 of the GNU GPL. - - 2. Conveying Modified Versions. - - If you modify a copy of the Library, and, in your modifications, a -facility refers to a function or data to be supplied by an Application -that uses the facility (other than as an argument passed when the -facility is invoked), then you may convey a copy of the modified -version: - - a) under this License, provided that you make a good faith effort to - ensure that, in the event an Application does not supply the - function or data, the facility still operates, and performs - whatever part of its purpose remains meaningful, or - - b) under the GNU GPL, with none of the additional permissions of - this License applicable to that copy. - - 3. Object Code Incorporating Material from Library Header Files. - - The object code form of an Application may incorporate material from -a header file that is part of the Library. You may convey such object -code under terms of your choice, provided that, if the incorporated -material is not limited to numerical parameters, data structure -layouts and accessors, or small macros, inline functions and templates -(ten or fewer lines in length), you do both of the following: - - a) Give prominent notice with each copy of the object code that the - Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the object code with a copy of the GNU GPL and this license - document. - - 4. Combined Works. - - You may convey a Combined Work under terms of your choice that, -taken together, effectively do not restrict modification of the -portions of the Library contained in the Combined Work and reverse -engineering for debugging such modifications, if you also do each of -the following: - - a) Give prominent notice with each copy of the Combined Work that - the Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the Combined Work with a copy of the GNU GPL and this license - document. - - c) For a Combined Work that displays copyright notices during - execution, include the copyright notice for the Library among - these notices, as well as a reference directing the user to the - copies of the GNU GPL and this license document. - - d) Do one of the following: - - 0) Convey the Minimal Corresponding Source under the terms of this - License, and the Corresponding Application Code in a form - suitable for, and under terms that permit, the user to - recombine or relink the Application with a modified version of - the Linked Version to produce a modified Combined Work, in the - manner specified by section 6 of the GNU GPL for conveying - Corresponding Source. - - 1) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (a) uses at run time - a copy of the Library already present on the user's computer - system, and (b) will operate properly with a modified version - of the Library that is interface-compatible with the Linked - Version. - - e) Provide Installation Information, but only if you would otherwise - be required to provide such information under section 6 of the - GNU GPL, and only to the extent that such information is - necessary to install and execute a modified version of the - Combined Work produced by recombining or relinking the - Application with a modified version of the Linked Version. (If - you use option 4d0, the Installation Information must accompany - the Minimal Corresponding Source and Corresponding Application - Code. If you use option 4d1, you must provide the Installation - Information in the manner specified by section 6 of the GNU GPL - for conveying Corresponding Source.) - - 5. Combined Libraries. - - You may place library facilities that are a work based on the -Library side by side in a single library together with other library -facilities that are not Applications and are not covered by this -License, and convey such a combined library under terms of your -choice, if you do both of the following: - - a) Accompany the combined library with a copy of the same work based - on the Library, uncombined with any other library facilities, - conveyed under the terms of this License. - - b) Give prominent notice with the combined library that part of it - is a work based on the Library, and explaining where to find the - accompanying uncombined form of the same work. - - 6. Revised Versions of the GNU Lesser General Public License. - - The Free Software Foundation may publish revised and/or new versions -of the GNU Lesser General Public License from time to time. Such new -versions will be similar in spirit to the present version, but may -differ in detail to address new problems or concerns. - - Each version is given a distinguishing version number. If the -Library as you received it specifies that a certain numbered version -of the GNU Lesser General Public License "or any later version" -applies to it, you have the option of following the terms and -conditions either of that published version or of any later version -published by the Free Software Foundation. If the Library as you -received it does not specify a version number of the GNU Lesser -General Public License, you may choose any version of the GNU Lesser -General Public License ever published by the Free Software Foundation. - - If the Library as you received it specifies that a proxy can decide -whether future versions of the GNU Lesser General Public License shall -apply, that proxy's public statement of acceptance of any version is -permanent authorization for you to choose that version for the -Library. +3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. +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. diff --git a/README.md b/README.md index 6a516b7..dd24461 100644 --- a/README.md +++ b/README.md @@ -5,332 +5,37 @@ Status](https://travis-ci.org/druids/django-chamber.svg?branch=master)](https:// [![Codacy Badge](https://api.codacy.com/project/badge/Grade/012d28c820fd4b19a783618c05d7a0a9)](https://www.codacy.com/app/lukas-rychtecky/django-chamber?utm_source=github.com&utm_medium=referral&utm_content=druids/django-chamber&utm_campaign=badger) [![Coverage Status](https://coveralls.io/repos/github/druids/django-chamber/badge.svg?branch=master)](https://coveralls.io/github/druids/django-chamber?branch=master) +[![Licence](https://img.shields.io/badge/License-BSD%203--Clause-blue.svg)](https://opensource.org/licenses/BSD-3-Clause) -This library contains useful functions and classes mainly for a web development with Django (form and model fields, -shortcuts, advanced datastructure, decoraters etc.). For more details see examples below. +Chamber contains a collection of useful base model classes, form fields, model fields, decorators, or other shortcuts to aid web development in Django. -## Reference +One can think of it as a toolbox with utilities that were too small to justify creating a standalone library and therefore ended up here. Hence the name **Chamber**. -### 1. Forms +## Features -#### `chamber.forms.fields.DecimalField` +The most noteworthy part of Chamber is the alternative base class for Django models called `SmartModel`. It provides following additional features: -`django.forms.NumberInput` with `step` parameter and validated `min` and `max` parameters. +Other useful components include: -#### `chamber.forms.widgets.ReadonlyWidget` +* AuditModel -- adds `created_at` and `changed_at` fields to the basic Django model, +* SmartQuerySet -- adds `fast_distinct` method to querysets (useful for PostgreSQL), +* several enum classes such as `ChoicesNumEnum` or `SequenceChoiceEnum`, +* new Django-style shortcuts such as `get_object_or_none`, `change_and_save`, or `bulk_change_and_save`. +* `MigrationLoadFixture` class that supports loading Django fixtures inside a database migration +* ...and more. -Widget for safe rendering of readonly form values. +## Contributing & Documentation -#### `chamber.forms.fields.PriceField` +You are welcomed to contribute at https://github.com/druids/django-chamber. There is an example project in the repository. Your feature should be added to this example project with tests as well as the documentation. -`django.forms.NumberInput` with `currency` as a placeholder. +1. Go to the `example` directory and call `make install` to install it. +2. Run tests using `make test`. -### 2. Models - -#### `chamber.models.fields.SouthMixin` - -Mixin for automatic South migration of custom model fields. - -#### `chamber.models.fields.DecimalField` - -`django.db.models.DecimalField` with `step`, `min` and `max` parameters. Uses [`chamber.forms.fields.DecimalField`](#chamberformsfieldsdecimalfield) as default form field. - -#### `chamber.models.fields.RestrictedFileFieldMixin` - -Same as FileField, but you can specify: -* `allowed_content_types` - list containing allowed content_types. Example: ['application/pdf', 'image/jpeg'] -* `max_upload_size` - a number indicating the maximum file size allowed for upload in MB. -Maximum upload size can be specified in project settings under `MAX_FILE_UPLOAD_SIZE` constant - -#### `chamber.models.fields.FileField` - -`django.db.models.FileField` with [`RestrictedFileFieldMixin`](#chambermodelsfieldsrestrictedfilefieldmixin) options. - -#### `chamber.models.fields.ImageField` - -`sorl.thumbnail.ImageField` (fallback to `django.db.models.ImageField`) with [`RestrictedFileFieldMixin`](#chambermodelsfieldsrestrictedfilefieldmixin) options. - -#### `chamber.models.fields.CharNullField` - -`django.db.models.CharField` that stores `NULL` but returns ''. - -#### `chamber.models.fields.PriceField` - -`chamber.models.fields.DecimalField` with defaults: - -- `currency` as `CZK` -- `decimal_places` as `2` -- `max_digits` as `10` -- `humanized` value for a pretty printing via `chamber.models.humanized_helpers.price_humanized` - -#### `chamber.models.fields.PositivePriceField` - -`chamber.models.fields.PriceField` with a default `django.core.validators.MinValueValidator` set to `0.00`. - - -### 3. SmartQuerySet `chamber.models.SmartQuerySet` -SmartModel introduced to Chamber uses by default a modified QuerySet with some convenience filters. - -If you are overriding model manager of a SmartModel, you should incorporate `SmartQuerySet` in order not to lose its benefits and to follow the Rule of the Least Surprise (everyone using your SmartModel will assume the custom filters to be there). - -1. If the manager is created using the `QuerySet.as_manager()` method, your custom queryset should subclass `SmartQuerySet` instead the one from Django. -2. If you have a new manager created by subclassing `models.Manager` from Django, you should override the `get_queryset` method as shown in Django docs [here](https://docs.djangoproject.com/en/1.10/topics/db/managers/#calling-custom-queryset-methods-from-the-manager). - -List of the added filters follows. - -#### 3.1 `fast_distinct()` -Returns same result as regular `distinct()` but is much faster especially in PostgreSQL which performs distinct on all DB columns. The optimization is achieved by doing a second query and the `__in` operator. If you have queryset `qs` of `MyModel` then `fast_distinct()` equals to calling -```python -MyModel.objects.filter(pk__in=qs.values_list('pk', flat=True)) -``` - - -### 4. Model Dispatchers - -Model dispatchers are a way to reduce complexity of `_pre_save` and `_post_save` methods of the SmartModel. A common use-case of these methods is to perform some action based on the change of the model, e.g. send a notification e-mail when the state of the invoice changes. - -Better alternative is to define a handler function encapsulating the action that should happen when the model changes in a certain way. This handler is registered on the model using a proper dispatcher. - -So far, there are two types of dispatchers but you are free to subclass the `BaseDispatcher` class to create your own, see the code as reference. During save of the model, the `__call__` method of all dispatchers is invoked with following parameters: - -1. `obj` ... instance of the model that is being saved -2. `changed_fields` ... list of field names that was changed since the last save -3. `*args` ... custom arguments passed to the save method (can be used to pass additional arguments to your custom dispatchers) -4. `**kwargs` ... custom keyword arguments passed to the save method - -The moment when the handler should be fired may be important. Therefore, you can register the dispatcher either in the `pre_save_dispatchers` group or `post_save_dispatchers` group. Both groups are dispatched immediately after the `_pre_save` or `_post_save` method respectively. - -When the handler is fired, it is passed a single argument -- the instance of the SmartModel that is being saved. Here is an example of a handler that is registered on a `User` model: -```python -def send_email(user): - # Code that actually sends the e-mail - send_html_email(recipient=user.email, subject='Your profile was updated') -``` - -#### 4.1 Property Dispatcher -`chamber.models.dispatchers.PropertyDispatcher` is a versatile dispatcher that fires the given handler when a specified property of the model evaluates to `True`. - -The example shows how to to register the aforementioned `send_email` handler to be dispatched after saving the object if the property `should_send_email` returns `True`. -```python -class MySmartModel(chamber_models.SmartModel): - - email_sent = models.BooleanField() - - post_save_dispatchers = ( - PropertyDispatcher(send_email, 'should_send_email'), - ) - - @property - def should_send_email(self): - return not self.email_sent -``` - -#### 4.2 State Dispatcher -In the following example, where we register `my_handler` function to be dispatched during `_pre_save` method when the state changes to `SECOND`. This is done using `chamber.models.dispatchers.StateDispatcher`. - -```python -def my_handler(my_smart_model): - # Do that useful stuff - pass - - -class MySmartModel(chamber_models.SmartModel): - - STATE = ChoicesNumEnum( - ('FIRST', _('first'), 1), - ('SECOND', _('second'), 2), - ) - state = models.IntegerField(choices=STATE.choices, default=STATE.FIRST) - - pre_save_dispatchers = ( - StateDispatcher(my_handler, STATE, state, STATE.SECOND), - ) -``` - -#### 4.2 State Dispatcher -A common use-case is to perform an action whenever an instance of a particular model is created. `chamber.models.dispatchers.CreatedDispatcher` is provided to accommodate this need. An update of the instance will not trigger the handler. - -```python -def my_handler(my_smart_model): - # Do that useful stuff when a new instance of MySmartModel is created - pass - - -class MySmartModel(chamber_models.SmartModel): - - post_save_dispatchers = ( - CreatedDispatcher(my_handler), - ) -``` - -### Utils - -#### `chamber.utils.remove_accent` - -```python -remove_accent('ěščřžýáíé') # 'escrzyaie' -``` - -#### `chamber.utils.get_class_method` - -It returns a method of a given class or instance. - -#### `chamber.utils.datastructures.AbstractEnum` - -Base enumeration class with controlled `__getattr__`. - -#### `chamber.utils.datastructures.Enum` - -Python's `set` with [`AbstractEnum`](#chamberutilsdatastructuresabstractenum) behaviour. - -#### `chamber.utils.datastructures.NumEnum` - -Python's `dict` with [`AbstractEnum`](#chamberutilsdatastructuresabstractenum) behaviour. - -```python -NumEnum('a', 'b') # {'a': 1, 'b': 2} -``` - -#### `chamber.utils.datastructures.AbstractChoicesEnum` - -Base choices class (as used in Model field's `choices` argument). - -#### `chamber.utils.datastructures.ChoicesEnum` - -`django.utils.datastructures.SortedDict` with [`AbstractEnum`](#chamberutilsdatastructuresabstractenum) and [`AbstractChoicesEnum`](#chamberutilsdatastructuresabstractenum) behaviour. Useful for string based choices. - -```python -enum = ChoicesEnum(('OK', 'ok'), ('KO', 'ko')) # {'OK': 'ok', 'KO': 'ko'} -enum.OK # 'ok' -enum.choices # [('OK', 'ok'), ('KO', 'ko')] -``` - -#### `chamber.utils.datastructures.ChoicesNumEnum` - -`django.utils.datastructures.SortedDict` with [`AbstractEnum`](#chamberutilsdatastructuresabstractenum) and [`AbstractChoicesEnum`](#chamberutilsdatastructuresabstractenum) behaviour. Useful for integer based choices. - -```python -enum = ChoicesNumEnum(('OK', 'ok', 1), ('KO', 'ko', 2)) -enum.KO # 2 -enum.choices # [(1, 'ok'), (2, 'ko')] -enum.get_label(2) # 'ko' -``` - -#### `chamber.utils.decorators.classproperty` - -Ties property to class, usefull for usage in class methods. - -```python -class RestResource(BaseResource): - @classproperty - def csrf_exempt(cls): - return not cls.login_required - - @classmethod - def as_view(cls, allowed_methods=None, **initkwargs): - view.csrf_exempt = cls.csrf_exempt -``` - -#### `chamber.utils.decorators.singleton` - -Class decorator, which allows for only one instance of class to exist. - -#### `chamber.utils.decorators.short_description` - -Sets `short_description` attribute (this attribute is used by list_display and formulars). - -```python -@short_description('amount') -def absolute_amount(self): - return abs(self.amount) -``` - -is equivalent of - -```python -def absolute_amount(self): - return abs(self.amount) -absolute_amount.short_description = 'amount' -``` - -#### `chamber.utils.forms.formset_has_file_field` - -Returns True if passed formset contains FileField (or ImageField). - -#### `chamber.utils.http.query_string_from_dict` - -Assemble query string from `dict` of parameters. - -```python -query_string_from_dict({'q': 'query1', 'user': 'test'}) # u'q=query1&user=test' -``` - -### Shortcuts - -#### `chamber.shortcuts.get_object_or_none` - -Takes Model or QuerySet and arguments and returns instance of Model if exists, `None` otherwise. - -```python -get_object_or_none(User, pk=1) # -get_object_or_none(User.objects.exclude(pk=1), pk=1) or '' # '' -``` - -#### `chamber.shortcuts.get_object_or_404` - -Takes Model or QuerySet and arguments and returns instance of Model if exists, raises `django.http.response.Http404` otherwise. - -```python -get_object_or_404(User, pk=1) # -get_object_or_404(User.objects.exclude(pk=1), pk=1) -Traceback (most recent call last): - File "", line 1, in - File "/var/ve/lib/python2.7/site-packages/chamber/shortcuts.py", line 21, in get_object_or_404 - raise Http404 -Http404 -``` - -#### `chamber.shortcuts.distinct_field` - -Takes Model or QuerySet and distinction parameters and returns list of unique values. - -```python -User.objects.filter(last_name='Gaul') # [, ] -distinct_field(User.objects.filter(last_name='Gaul'), 'last_name') # [(u'Gaul',)] -``` - -#### `chamber.shortcuts.filter_or_exclude_by_date` - -Takes negate `bool` (True for exclude, False for filter), Model or QuerySet and date parameters and return queryset filtered or excluded by date parameters. - -```python -Order.objects.values_list('created_at', flat=True) # [datetime.datetime(2014, 4, 6, 15, 56, 16, 727000, tzinfo=), - # datetime.datetime(2014, 2, 6, 15, 56, 16, 727000, tzinfo=), - # datetime.datetime(2014, 1, 11, 23, 15, 43, 727000, tzinfo=)] -filter_or_exclude_by_date(False, Order, created_at=date(2014, 2, 6)) # [] -filter_or_exclude_by_date(False, Order, created_at=date(2014, 2, 6))[0].created_at # datetime.datetime(2014, 2, 6, 15, 56, 16, 727000, tzinfo=) -``` - -#### `chamber.shortcuts.filter_by_date` - -Shortcut for [`chamber.shortcuts.filter_or_exclude_by_date`](#chambershortcutsfilter_or_exclude_by_date) with first parameter False. - -#### `chamber.shortcuts.exclude_by_date` - -Shortcut for [`chamber.shortcuts.filter_or_exclude_by_date`](#chambershortcutsfilter_or_exclude_by_date) with first parameter True. - - -Development ------------ - -For contribution go to `example` directory and call `make install` to install an example project. - -Testing -------- - -To run tests go to `example` directory and call `make test`. +## Known Issues +* documentation of this library is a work in progress, needs a lot of attention +* SmartModel extends the AuditModel and therefore always adds `created_at` and `changed_at` fields to the model which is not always desirable ## License -See LICENSE file. +This library is licenced under the 3-clause BSD licence. See the LICENCE file for details. diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000..e17d99a --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,192 @@ +# Makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +PAPER = +BUILDDIR = .build + +# User-friendly check for sphinx-build +ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) +$(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/) +endif + +# Internal variables. +PAPEROPT_a4 = -D latex_paper_size=a4 +PAPEROPT_letter = -D latex_paper_size=letter +ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . +# the i18n builder cannot share the environment and doctrees with the others +I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . + +.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest coverage gettext + +help: + @echo "Please use \`make ' where is one of" + @echo " html to make standalone HTML files" + @echo " dirhtml to make HTML files named index.html in directories" + @echo " singlehtml to make a single large HTML file" + @echo " pickle to make pickle files" + @echo " json to make JSON files" + @echo " htmlhelp to make HTML files and a HTML help project" + @echo " qthelp to make HTML files and a qthelp project" + @echo " applehelp to make an Apple Help Book" + @echo " devhelp to make HTML files and a Devhelp project" + @echo " epub to make an epub" + @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" + @echo " latexpdf to make LaTeX files and run them through pdflatex" + @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" + @echo " text to make text files" + @echo " man to make manual pages" + @echo " texinfo to make Texinfo files" + @echo " info to make Texinfo files and run them through makeinfo" + @echo " gettext to make PO message catalogs" + @echo " changes to make an overview of all changed/added/deprecated items" + @echo " xml to make Docutils-native XML files" + @echo " pseudoxml to make pseudoxml-XML files for display purposes" + @echo " linkcheck to check all external links for integrity" + @echo " doctest to run all doctests embedded in the documentation (if enabled)" + @echo " coverage to run coverage check of the documentation (if enabled)" + +clean: + rm -rf $(BUILDDIR)/* + +html: + $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." + +dirhtml: + $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." + +singlehtml: + $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml + @echo + @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." + +pickle: + $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle + @echo + @echo "Build finished; now you can process the pickle files." + +json: + $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json + @echo + @echo "Build finished; now you can process the JSON files." + +htmlhelp: + $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp + @echo + @echo "Build finished; now you can run HTML Help Workshop with the" \ + ".hhp project file in $(BUILDDIR)/htmlhelp." + +qthelp: + $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp + @echo + @echo "Build finished; now you can run "qcollectiongenerator" with the" \ + ".qhcp project file in $(BUILDDIR)/qthelp, like this:" + @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/django-is-core.qhcp" + @echo "To view the help file:" + @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/django-is-core.qhc" + +applehelp: + $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp + @echo + @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." + @echo "N.B. You won't be able to view it unless you put it in" \ + "~/Library/Documentation/Help or install it in your application" \ + "bundle." + +devhelp: + $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp + @echo + @echo "Build finished." + @echo "To view the help file:" + @echo "# mkdir -p $$HOME/.local/share/devhelp/django-is-core" + @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/django-is-core" + @echo "# devhelp" + +epub: + $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub + @echo + @echo "Build finished. The epub file is in $(BUILDDIR)/epub." + +latex: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo + @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." + @echo "Run \`make' in that directory to run these through (pdf)latex" \ + "(use \`make latexpdf' here to do that automatically)." + +latexpdf: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through pdflatex..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +latexpdfja: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through platex and dvipdfmx..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +text: + $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text + @echo + @echo "Build finished. The text files are in $(BUILDDIR)/text." + +man: + $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man + @echo + @echo "Build finished. The manual pages are in $(BUILDDIR)/man." + +texinfo: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo + @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." + @echo "Run \`make' in that directory to run these through makeinfo" \ + "(use \`make info' here to do that automatically)." + +info: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo "Running Texinfo files through makeinfo..." + make -C $(BUILDDIR)/texinfo info + @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." + +gettext: + $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale + @echo + @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." + +changes: + $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes + @echo + @echo "The overview file is in $(BUILDDIR)/changes." + +linkcheck: + $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck + @echo + @echo "Link check complete; look for any errors in the above output " \ + "or in $(BUILDDIR)/linkcheck/output.txt." + +doctest: + $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest + @echo "Testing of doctests in the sources finished, look at the " \ + "results in $(BUILDDIR)/doctest/output.txt." + +coverage: + $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage + @echo "Testing of coverage in the sources finished, look at the " \ + "results in $(BUILDDIR)/coverage/python.txt." + +xml: + $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml + @echo + @echo "Build finished. The XML files are in $(BUILDDIR)/xml." + +pseudoxml: + $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml + @echo + @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 0000000..95e6f5d --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,358 @@ +# -*- coding: utf-8 -*- +# +# django-chamber documentation build configuration file, created by +# sphinx-quickstart on Wed Aug 26 20:27:52 2015. +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +#sys.path.insert(0, os.path.abspath('.')) + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +#needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + 'sphinx.ext.intersphinx', + 'sphinx.ext.todo', + 'sphinx.ext.viewcode', +] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['.templates'] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# source_suffix = ['.rst', '.md'] +source_suffix = '.rst' + +# The encoding of source files. +#source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = u'django-chamber' +copyright = u'2017, Luboš Mátl, Lukáš Rychtecký, Oskar Hollmann' # pylint: disable=W0622 +author = u'Luboš Mátl, Lukáš Rychtecký Oskar Hollmann' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = '0.2' +# The full version, including alpha/beta/rc tags. +release = '0.2.0' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +#today = '' +# Else, today_fmt is used as the format for a strftime call. +#today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ['.build'] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +#default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +#add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +#add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +#show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +#modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +#keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = 'sphinx_rtd_theme' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +#html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +#html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +#html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +#html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +#html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +#html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['.static'] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +#html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +#html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +#html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +#html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +#html_additional_pages = {} + +# If false, no module index is generated. +#html_domain_indices = True + +# If false, no index is generated. +#html_use_index = True + +# If true, the index is split into individual pages for each letter. +#html_split_index = False + +# If true, links to the reST sources are added to the pages. +#html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +#html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +#html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +#html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +#html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +#html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +#html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +#html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = 'django-chamberdoc' + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { +# The paper size ('letterpaper' or 'a4paper'). +#'papersize': 'letterpaper', + +# The font size ('10pt', '11pt' or '12pt'). +#'pointsize': '10pt', + +# Additional stuff for the LaTeX preamble. +#'preamble': '', + +# Latex figure (float) alignment +#'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + (master_doc, 'django-chamber.tex', u'django-chamber Documentation', + u'Luboš Mátl, Lukáš Rychtecký, Oskar Hollmann', 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +#latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +#latex_use_parts = False + +# If true, show page references after internal links. +#latex_show_pagerefs = False + +# If true, show URL addresses after external links. +#latex_show_urls = False + +# Documents to append as an appendix to all manuals. +#latex_appendices = [] + +# If false, no module index is generated. +#latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + (master_doc, 'django-chamber', u'django-chamber Documentation', + [author], 1) +] + +# If true, show URL addresses after external links. +#man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + (master_doc, 'django-chamber', u'django-chamber Documentation', + author, 'django-chamber', 'A collection of utilities to aid web development in Django.', + 'Miscellaneous'), +] + +# Documents to append as an appendix to all manuals. +#texinfo_appendices = [] + +# If false, no module index is generated. +#texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +#texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +#texinfo_no_detailmenu = False + + +# -- Options for Epub output ---------------------------------------------- + +# Bibliographic Dublin Core info. +epub_title = project +epub_author = author +epub_publisher = author +epub_copyright = copyright + +# The basename for the epub file. It defaults to the project name. +#epub_basename = project + +# The HTML theme for the epub output. Since the default themes are not optimized +# for small screen space, using the same theme for HTML and epub output is +# usually not wise. This defaults to 'epub', a theme designed to save visual +# space. +#epub_theme = 'epub' + +# The language of the text. It defaults to the language option +# or 'en' if the language is not set. +#epub_language = '' + +# The scheme of the identifier. Typical schemes are ISBN or URL. +#epub_scheme = '' + +# The unique identifier of the text. This can be a ISBN number +# or the project homepage. +#epub_identifier = '' + +# A unique identification for the text. +#epub_uid = '' + +# A tuple containing the cover image and cover page html template filenames. +#epub_cover = () + +# A sequence of (type, uri, title) tuples for the guide element of content.opf. +#epub_guide = () + +# HTML files that should be inserted before the pages created by sphinx. +# The format is a list of tuples containing the path and title. +#epub_pre_files = [] + +# HTML files shat should be inserted after the pages created by sphinx. +# The format is a list of tuples containing the path and title. +#epub_post_files = [] + +# A list of files that should not be packed into the epub file. +epub_exclude_files = ['search.html'] + +# The depth of the table of contents in toc.ncx. +#epub_tocdepth = 3 + +# Allow duplicate toc entries. +#epub_tocdup = True + +# Choose between 'default' and 'includehidden'. +#epub_tocscope = 'default' + +# Fix unsupported image types using the Pillow. +#epub_fix_images = False + +# Scale large images. +#epub_max_image_width = 0 + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +#epub_show_urls = 'inline' + +# If false, no index is generated. +#epub_use_index = True + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = {'https://docs.python.org/': None} diff --git a/docs/dispatchers.rst b/docs/dispatchers.rst new file mode 100644 index 0000000..cb602e8 --- /dev/null +++ b/docs/dispatchers.rst @@ -0,0 +1,89 @@ +Model Dispatchers +================= + +Model dispatchers are a way to reduce complexity of ``_pre_save`` and +``_post_save`` methods of the SmartModel. A common use-case of these +methods is to perform some action based on the change of the model, +e.g. send a notification e-mail when the state of the invoice changes. + +Better alternative is to define a handler function encapsulating the +action that should happen when the model changes in a certain way. This +handler is registered on the model using a proper dispatcher. + +.. class:: chamber.models.dispatchers.BaseDispatcher + +So far, there are two types of dispatchers but you are free to subclass +the ``BaseDispatcher`` class to create your own, see the code as +reference. During save of the model, the ``__call__`` method of all +dispatchers is invoked with following parameters: + +1. ``obj`` instance of the model that is being saved +2. ``changed_fields`` list of field names that was changed since the + last save +3. ``*args`` custom arguments passed to the save method (can be used + to pass additional arguments to your custom dispatchers) +4. ``**kwargs`` custom keyword arguments passed to the save method + +The moment when the handler should be fired may be important. +Therefore, you can register the dispatcher either in the ``pre_save_dispatchers`` +group or ``post_save_dispatchers`` group. +Both groups are dispatched immediately after the ``_pre_save`` or ``_post_save`` +method respectively. + +When the handler is fired, it is passed a single argument -- the instance of the SmartModel being saved. Here is an example of a handler registered on a ``User`` model: + +:: + + def send_email(user): + # Code that actually sends the e-mail + send_html_email(recipient=user.email, subject='Your profile was updated') + +.. class:: chamber.models.dispatchers.PropertyDispatcher + +``chamber.models.dispatchers.PropertyDispatcher`` is a versatile +dispatcher that fires the given handler when a specified property of the +model evaluates to ``True``. + +The example shows how to to register the aforementioned ``send_email`` +handler to be dispatched after saving the object if the property +``should_send_email`` returns ``True``. + +.. code:: python + + class MySmartModel(chamber_models.SmartModel): + + email_sent = models.BooleanField() + + post_save_dispatchers = ( + PropertyDispatcher(send_email, 'should_send_email'), + ) + + @property + def should_send_email(self): + return not self.email_sent + +.. class:: chamber.models.dispatchers.StateDispatcher + +``StateDispatcher`` can be used to dispatch a handler when a value of some model field +changes to a specific value. +In the following example, we register a ``my_handler`` function to +be dispatched during the ``_pre_save`` method when the state changes to +``SECOND``. + +.. code:: python + + def my_handler(my_smart_model): # Do that useful stuff + pass + + class MySmartModel(chamber\_models.SmartModel): + + + STATE = ChoicesNumEnum( + ('FIRST', _('first'), 1), + ('SECOND', _('second'), 2), + ) + state = models.IntegerField(choices=STATE.choices, default=STATE.FIRST) + + pre_save_dispatchers = ( + StateDispatcher(my_handler, STATE, state, STATE.SECOND), + ) diff --git a/docs/forms.rst b/docs/forms.rst new file mode 100644 index 0000000..65a252c --- /dev/null +++ b/docs/forms.rst @@ -0,0 +1,14 @@ +Forms +===== + +.. class:: chamber.forms.fields.DecimalField + +``django.forms.DecimalField`` with ``step``, ``min``, and ``max`` parameters. + +.. class:: chamber.forms.widgets.ReadonlyWidget + +A widget for safe rendering of readonly form values. + +.. class:: chamber.forms.fields.PriceField + +``django.forms.NumberInput`` with ``currency`` as a placeholder. diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 0000000..e604338 --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,76 @@ +.. django-chamber documentation master file, created by + sphinx-quickstart on Wed Aug 26 20:27:52 2015. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +############## +Django-chamber +############## + + +.. image:: https://travis-ci.org/druids/django-chamber.svg?branch=master + :target: https://travis-ci.org/druids/django-chamber + +.. image:: https://api.codacy.com/project/badge/Grade/012d28c820fd4b19a783618c05d7a0a9 + :target: https://www.codacy.com/app/lukas-rychtecky/django-chamber?utm_source=github.com&utm_medium=referral&utm_content=druids/django-chamber&utm_campaign=badger + +.. image:: https://coveralls.io/repos/github/druids/django-chamber/badge.svg?branch=master + :target: https://coveralls.io/github/druids/django-chamber?branch=master + +.. image:: https://img.shields.io/badge/License-BSD%203--Clause-blue.svg + :target: https://opensource.org/licenses/BSD-3-Clause + +Chamber contains a collection of useful base model classes, form fields, model fields, decorators, or other shortcuts to aid web development in Django. + +One can think of it as a toolbox with utilities that were too small to justify creating a standalone library and therefore ended up here. Hence the name *Chamber*. Its purpose is not unlike the discontinued `EasyMode `_ library. + +******** +Overview +******** + +Features +======== +The most noteworthy part of Chamber is the alternative base class for Django models called :code:`SmartModel`. It provides following additional features: + +* adds :code:`created_at` and :code:`changed_at` datetime fields on derived models, +* splits the save method of Django model into several methods :code:`_pre_save`, :code:`_save`, :code:`_post_save` for readability, +* keeps track of whether the instance being saved is a new one or whether it is an update to an existing one, +* keeps track of which fields changed during the save method and this info is available even in the :code:`_post_save` method, +* provides way to unclutter the save methods by declaring several types of **model dispatchers**, useful e.g. for sending notifications based on changes on the instance. + +Other useful components include: + +* AuditModel -- adds :code:`created_at` and :code:`changed_at` fields to the basic Django model, +* SmartQuerySet -- adds :code:`fast_distinct` method to querysets (useful for PostgreSQL), +* several enum classes such as :code:`ChoicesNumEnum` or :code:`SequenceChoiceEnum`, +* new Django-style shortcuts such as :code:`get_object_or_none`, :code:`change_and_save`, or :code:`bulk_change_and_save`. +* :code:`MigrationLoadFixture` class that supports loading Django fixtures inside a database migration +* ...and more. + +Contributing & Documentation +============================ +You are welcomed to contribute at https://github.com/druids/django-chamber. There is an example project in the repository. Your feature should be added to this example project with tests as well as the documentation. + +# Go to the `example` directory and call `make install` to install it. +# Run tests using `make test`. + +Documentation is available at https://django-chamber.readthedocs.org/en/latest. + +Known Issues +============ +* this documentation is a work in progress, needs a lot of attention +* SmartModel extends the AuditModel and therefore always adds `created_at` and `changed_at` fields to the model which is not always desirable + +******* +Content +******* + +.. toctree:: + :maxdepth: 5 + + installation + forms + models + dispatchers + utils + shortcuts diff --git a/docs/installation.rst b/docs/installation.rst new file mode 100644 index 0000000..29cebe9 --- /dev/null +++ b/docs/installation.rst @@ -0,0 +1,43 @@ +.. _installation: + +Installation +============ + +Python/Django versions +---------------------- + ++----------------------+------------+ +| Python | Django | ++======================+============+ +| 2.7, 3.4, 3.5, 3.6 | 1.7 - 1.10 | ++----------------------+------------+ + + +Requirements +------------ + + * **django** -- Chamber extends Django, therefore it is a natural dependency + * **pyprind** -- used in CSV importers to show progress bars + * **six** -- to provide Python 2/3 compatibility + * **filemagic** + * **unidecode** + + +Using Pip +--------- +Django-chamber is not currently inside *PyPI* but in the future you will be able to use: + +.. code-block:: console + + $ pip install django-chamber + + +Because *django-chamber* is a rapidly evolving library, the best way to install is use the source from github + +.. code-block:: console + + $ pip install https://github.com/druids/django-chamber/tarball/{{ version }}#egg=django-chamber-{{ version }} + +Configuration +------------- +No configuration is required as this is a utility library. Just import the stuff you need. diff --git a/docs/make.bat b/docs/make.bat new file mode 100644 index 0000000..5c5d8c9 --- /dev/null +++ b/docs/make.bat @@ -0,0 +1,263 @@ +@ECHO OFF + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set BUILDDIR=.build +set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . +set I18NSPHINXOPTS=%SPHINXOPTS% . +if NOT "%PAPER%" == "" ( + set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% + set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% +) + +if "%1" == "" goto help + +if "%1" == "help" ( + :help + echo.Please use `make ^` where ^ is one of + echo. html to make standalone HTML files + echo. dirhtml to make HTML files named index.html in directories + echo. singlehtml to make a single large HTML file + echo. pickle to make pickle files + echo. json to make JSON files + echo. htmlhelp to make HTML files and a HTML help project + echo. qthelp to make HTML files and a qthelp project + echo. devhelp to make HTML files and a Devhelp project + echo. epub to make an epub + echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter + echo. text to make text files + echo. man to make manual pages + echo. texinfo to make Texinfo files + echo. gettext to make PO message catalogs + echo. changes to make an overview over all changed/added/deprecated items + echo. xml to make Docutils-native XML files + echo. pseudoxml to make pseudoxml-XML files for display purposes + echo. linkcheck to check all external links for integrity + echo. doctest to run all doctests embedded in the documentation if enabled + echo. coverage to run coverage check of the documentation if enabled + goto end +) + +if "%1" == "clean" ( + for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i + del /q /s %BUILDDIR%\* + goto end +) + + +REM Check if sphinx-build is available and fallback to Python version if any +%SPHINXBUILD% 2> nul +if errorlevel 9009 goto sphinx_python +goto sphinx_ok + +:sphinx_python + +set SPHINXBUILD=python -m sphinx.__init__ +%SPHINXBUILD% 2> nul +if errorlevel 9009 ( + echo. + echo.The 'sphinx-build' command was not found. Make sure you have Sphinx + echo.installed, then set the SPHINXBUILD environment variable to point + echo.to the full path of the 'sphinx-build' executable. Alternatively you + echo.may add the Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.http://sphinx-doc.org/ + exit /b 1 +) + +:sphinx_ok + + +if "%1" == "html" ( + %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/html. + goto end +) + +if "%1" == "dirhtml" ( + %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. + goto end +) + +if "%1" == "singlehtml" ( + %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. + goto end +) + +if "%1" == "pickle" ( + %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the pickle files. + goto end +) + +if "%1" == "json" ( + %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the JSON files. + goto end +) + +if "%1" == "htmlhelp" ( + %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run HTML Help Workshop with the ^ +.hhp project file in %BUILDDIR%/htmlhelp. + goto end +) + +if "%1" == "qthelp" ( + %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run "qcollectiongenerator" with the ^ +.qhcp project file in %BUILDDIR%/qthelp, like this: + echo.^> qcollectiongenerator %BUILDDIR%\qthelp\django-is-core.qhcp + echo.To view the help file: + echo.^> assistant -collectionFile %BUILDDIR%\qthelp\django-is-core.ghc + goto end +) + +if "%1" == "devhelp" ( + %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. + goto end +) + +if "%1" == "epub" ( + %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The epub file is in %BUILDDIR%/epub. + goto end +) + +if "%1" == "latex" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "latexpdf" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + cd %BUILDDIR%/latex + make all-pdf + cd %~dp0 + echo. + echo.Build finished; the PDF files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "latexpdfja" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + cd %BUILDDIR%/latex + make all-pdf-ja + cd %~dp0 + echo. + echo.Build finished; the PDF files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "text" ( + %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The text files are in %BUILDDIR%/text. + goto end +) + +if "%1" == "man" ( + %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The manual pages are in %BUILDDIR%/man. + goto end +) + +if "%1" == "texinfo" ( + %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. + goto end +) + +if "%1" == "gettext" ( + %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The message catalogs are in %BUILDDIR%/locale. + goto end +) + +if "%1" == "changes" ( + %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes + if errorlevel 1 exit /b 1 + echo. + echo.The overview file is in %BUILDDIR%/changes. + goto end +) + +if "%1" == "linkcheck" ( + %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck + if errorlevel 1 exit /b 1 + echo. + echo.Link check complete; look for any errors in the above output ^ +or in %BUILDDIR%/linkcheck/output.txt. + goto end +) + +if "%1" == "doctest" ( + %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest + if errorlevel 1 exit /b 1 + echo. + echo.Testing of doctests in the sources finished, look at the ^ +results in %BUILDDIR%/doctest/output.txt. + goto end +) + +if "%1" == "coverage" ( + %SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage + if errorlevel 1 exit /b 1 + echo. + echo.Testing of coverage in the sources finished, look at the ^ +results in %BUILDDIR%/coverage/python.txt. + goto end +) + +if "%1" == "xml" ( + %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The XML files are in %BUILDDIR%/xml. + goto end +) + +if "%1" == "pseudoxml" ( + %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. + goto end +) + +:end diff --git a/docs/models.rst b/docs/models.rst new file mode 100644 index 0000000..b6dd417 --- /dev/null +++ b/docs/models.rst @@ -0,0 +1,100 @@ +Models +====== + +Model Fields +------------ + +.. class:: chamber.models.fields.DecimalField + +Same as ``django.db.models.DecimalField`` but with additional attributes. Uses ``chamber.forms.fields.DecimalField`` as the default form field. + + .. attribute:: min + + A minimal value of the field. An appropriate ``MinValueValidator`` is added automatically. The HTML ``min`` component is added to the form field. + + .. attribute:: max + + A maximal value of the field. An appropriate ``MaxValueValidator`` is added automatically. The HTML ``max`` component is added to the form field. + + .. attribute:: step + + The step between values that is set on the form field. + +.. class:: chamber.models.fields.RestrictedFileFieldMixin + +Same as FileField, but you can specify: + + .. attribute:: allowed_content_types + + A list containing allowed content types, e.g. ``['application/pdf', 'image/jpeg']`` + + .. attribute:: max_upload_size + + A number indicating the maximum file size allowed for upload in MB. The maximum upload size can be specified in project settings as ``MAX_FILE_UPLOAD_SIZE`` + +.. class:: chamber.models.fields.FileField + +The ``django.db.models.FileField`` with ``RestrictedFileFieldMixin`` options. + +.. class:: chamber.models.fields.ImageField + +``sorl.thumbnail.ImageField`` with fallback to ``django.db.models.ImageField`` when ``sorl`` is not installed. Supports ``RestrictedFileFieldMixin`` options. + +.. class:: chamber.models.fields.CharNullField + +``django.db.models.CharField`` that stores ``NULL`` but returns ``''`` . + +.. class:: chamber.models.fields.PriceField + +``chamber.models.fields.DecimalField`` with defaults: + + .. attribute:: currency + + For example ``'CZK'``. + + .. attribute:: decimal_places + + Number of digits reserved for the decimal part of the number. + + .. attribute:: max_digits + + Max number of digits reserved for the field. + + .. attribute:: humanized + + Humanized value for a pretty printing via ``chamber.models.humanized_helpers.price_humanized`` + +.. class:: chamber.models.fields.PositivePriceField + +``chamber.models.fields.PriceField`` with a default ``django.core.validators.MinValueValidator`` set to ``0.00``. + +.. class:: chamber.models.fields.SouthMixin + +Mixin for automatic South migration of custom model fields. + +SmartQuerySet +------------- + +SmartModel uses a modified QuerySet by default with some convenience filters. + +If you are overriding model manager of a SmartModel, you should +incorporate ``SmartQuerySet`` in order not to lose its benefits and to +follow the Rule of the Least Surprise (everyone using your SmartModel +will assume the custom filters to be there). + +1. If the manager is created using the ``QuerySet.as_manager()`` method, + your custom queryset should subclass ``SmartQuerySet`` instead the + one from Django. +2. If you have a new manager created by subclassing ``models.Manager`` + from Django, you should override the ``get_queryset`` method as shown + in Django docs `here`_. + +.. class:: chamber.models.SmartQuerySet + + .. method:: fast_distinct() + + Returns same result as regular ``distinct()`` but is much faster especially in PostgreSQL which performs distinct on all DB columns. The optimization is achieved by doing a second query and the ``__in`` operator. If you have queryset ``qs`` of ``MyModel`` then ``fast_distinct()`` equals to calling + + .. code:: python + + MyModel.objects.filter(pk__in=qs.values_list('pk', flat=True)) diff --git a/docs/shortcuts.rst b/docs/shortcuts.rst new file mode 100644 index 0000000..96a1af5 --- /dev/null +++ b/docs/shortcuts.rst @@ -0,0 +1,67 @@ +Shortcuts +========= + +This is a collection of Django-styled shotcut function. + +.. function:: chamber.shortcuts.get_object_or_none + +Takes a Model or a QuerySet and some filter keyword arguments and returns an instance +of the Model if it exists, ``None`` otherwise. Similar to ``get_object_or_404`` in Django. + +:: + + >>> get_object_or_none(User, pk=1) + + >>> get_object_or_none(User.objects.exclude(pk=1), pk=1) or '' + +.. function:: chamber.shortcuts.get_object_or_404 + +Takes a Model or a QuerySet and some filter keyword arguments and returns an instance +of the Model if it exists, raises ``django.http.response.Http404`` otherwise. + +:: + + >>> get_object_or_404(User, pk=1) + + >>> get_object_or_404(User.objects.exclude(pk=1), pk=1) + Traceback (most recent call last): + File "", line 1, in + File "/var/ve/lib/python2.7/site-packages/chamber/shortcuts.py", line 21, in get_object_or_404 + raise Http404 + Http404 + +.. function:: chamber.shortcuts.distinct_field + +Takes a Model or a QuerySet. The rest of the args are the fields whose unique values should be returned. + +:: + + >>> User.objects.filter(last_name='Gaul') + [, ] + >>> distinct_field(User.objects.filter(last_name='Gaul'), 'last_name') + [(u'Gaul',)] + +.. function:: chamber.shortcuts.filter_or_exclude_by_date + +Takes a ``bool`` (True for exclude, False for filter), Model or +QuerySet and date parameters and return queryset filtered or excluded by +these date parameters. + +:: + + >>> Order.objects.values_list('created_at', flat=True) + [datetime.datetime(2014, 4, 6, 15, 56, 16, 727000, tzinfo=), + datetime.datetime(2014, 2, 6, 15, 56, 16, 727000, tzinfo=), + datetime.datetime(2014, 1, 11, 23, 15, 43, 727000, tzinfo=)] + >>> filter_or_exclude_by_date(False, Order, created_at=date(2014, 2, 6)) + [] + >>> filter_or_exclude_by_date(False, Order, created_at=date(2014, 2, 6))[0].created_at + datetime.datetime(2014, 2, 6, 15, 56, 16, 727000, tzinfo=) + +.. function:: chamber.shortcuts.filter_by_date + +Shortcut for ``chamber.shortcuts.filter_or_exclude_by_date`` with first parameter False. + +.. function:: chamber.shortcuts.exclude_by_date + +Shortcut for ``chamber.shortcuts.filter_or_exclude_by_date`` with first parameter True. diff --git a/docs/utils.rst b/docs/utils.rst new file mode 100644 index 0000000..e46c6e4 --- /dev/null +++ b/docs/utils.rst @@ -0,0 +1,114 @@ +Utils +===== + +Utility Functions +----------------- + +.. function:: chamber.utils.remove_accent(string_with_diacritics) + +.. code:: python + remove_accent('ěščřžýáíé') # 'escrzyaie' + +.. function:: chamber.utils.get_class_method(cls_or_inst, method_name) +Returns a method of a given class or instance. + + +.. function:: chamber.utils.forms.formset_has_file_field + +Returns True if passed formset contains FileField (or ImageField). + +.. function:: chamber.utils.http.query_string_from_dict + +Assembles query string from a Python ``dict``. +:: + + >>> query_string_from_dict({'q': 'query1', 'user': 'test'}) + u'q=query1&user=test' + +Enums +----- + +.. class:: chamber.utils.datastructures.AbstractEnum +Base enumeration class with controlled ``__getattr__``. + +.. class:: chamber.utils.datastructures.Enum +Python's ``set`` with ``AbstractEnum`` behaviour. + +.. class:: chamber.utils.datastructures.NumEnum +Python's ``dict`` with ``AbstractEnum`` behaviour. + +:: + + >>> NumEnum('a', 'b') + {'a': 1, 'b': 2} + +.. class:: chamber.utils.datastructures.AbstractChoicesEnum +Base choices class (can be used as a model field's ``choices`` argument). + +.. class:: chamber.utils.datastructures.ChoicesEnum +``django.utils.datastructures.SortedDict`` with ``AbstractEnum`` and +``AbstractChoicesEnum`` behaviour. Useful for string based choices. + +:: + + >>> enum = ChoicesEnum(('OK', 'ok'), ('KO', 'ko')) + >>> enum + {'OK': 'ok', 'KO': 'ko'} + >>> enum.OK + 'ok' + >>> enum.choices + [('OK', 'ok'), ('KO', 'ko')] + +.. class:: chamber.utils.datastructures.ChoicesNumEnum + +``django.utils.datastructures.SortedDict`` with ``AbstractEnum`` and +``AbstractChoicesEnum`` behaviour. Useful for integer-based choices. + +:: + + >>> enum = ChoicesNumEnum(('OK', 'ok', 1), ('KO', 'ko', 2)) + >>> enum.KO + 2 + >>> enum.choices + [(1, 'ok'), (2, 'ko')] + >>> enum.get_label(2) + 'ko' + +Decorators +---------- + +.. decorator:: chamber.utils.decorators.classproperty +Decorator that turns a class method into a property of the class. + +:: + + class RestResource(BaseResource): + @classproperty + def csrf_exempt(cls): + return not cls.login_required + + @classmethod + def as_view(cls, allowed_methods=None, **initkwargs): + view.csrf_exempt = cls.csrf_exempt + +.. decorator:: chamber.utils.decorators.singleton + +Class decorator, which allows for only one instance of class to exist. + +.. decorator:: chamber.utils.decorators.short_description + +Sets ``short_description`` attribute that is used to render description of a Django form field. + +:: + + @short_description('amount') + def absolute_amount(self): + return abs(self.amount) + +is equivalent to + +:: + + def absolute_amount(self): + return abs(self.amount) + absolute_amount.short_description = 'amount'