From e84a76979bb569a9d326ebf0ff9795668ffb946f Mon Sep 17 00:00:00 2001 From: Trey Hunner Date: Wed, 31 Jul 2013 22:55:43 -0700 Subject: [PATCH] Add initial documentation (based on README) --- docs/Makefile | 177 +++++++++++++++++ docs/conf.py | 248 ++++++++++++++++++++++++ docs/index.rst | 33 ++++ docs/make.bat | 242 +++++++++++++++++++++++ docs/setup.rst | 22 +++ docs/usage.rst | 508 +++++++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 1230 insertions(+) create mode 100644 docs/Makefile create mode 100644 docs/conf.py create mode 100644 docs/index.rst create mode 100644 docs/make.bat create mode 100644 docs/setup.rst create mode 100644 docs/usage.rst diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000..452f59f --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,177 @@ +# 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 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 " 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)" + +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-model-utils.qhcp" + @echo "To view the help file:" + @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/django-model-utils.qhc" + +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-model-utils" + @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/django-model-utils" + @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." + +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..15eaebf --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,248 @@ +# -*- coding: utf-8 -*- +# +# django-model-utils documentation build configuration file, created by +# sphinx-quickstart on Wed Jul 31 22:27:07 2013. +# +# 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. + +import sys, os + +# 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 = [] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix of source filenames. +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-model-utils' +copyright = u'2013, Carl Meyer' + +# 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 = '1.4' +# The full version, including alpha/beta/rc tags. +release = '1.4.0' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +#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 + + +# -- 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 = 'default' + +# 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'] + +# 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 + +# Output file base name for HTML help builder. +htmlhelp_basename = 'django-model-utilsdoc' + + +# -- 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': '', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, author, documentclass [howto/manual]). +latex_documents = [ + ('index', 'django-model-utils.tex', u'django-model-utils Documentation', + u'Carl Meyer', '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 = [ + ('index', 'django-model-utils', u'django-model-utils Documentation', + [u'Carl Meyer'], 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 = [ + ('index', 'django-model-utils', u'django-model-utils Documentation', + u'Carl Meyer', 'django-model-utils', 'One line description of project.', + '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 diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 0000000..2dd94ed --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,33 @@ +================== +django-model-utils +================== + +Django model mixins and utilities. + +Contents +======== + +.. toctree:: + :maxdepth: 3 + + setup + usage + +Contributing +============ + +Please file bugs and send pull requests to the `GitHub repository`_ and `issue +tracker`_. + +.. _GitHub repository: https://github.com/carljm/django-model-utils/ +.. _issue tracker: https://github.com/carljm/django-model-utils/issues + + + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` + diff --git a/docs/make.bat b/docs/make.bat new file mode 100644 index 0000000..fb1a0ef --- /dev/null +++ b/docs/make.bat @@ -0,0 +1,242 @@ +@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 + goto end +) + +if "%1" == "clean" ( + for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i + del /q /s %BUILDDIR%\* + goto end +) + + +%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 +) + +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-model-utils.qhcp + echo.To view the help file: + echo.^> assistant -collectionFile %BUILDDIR%\qthelp\django-model-utils.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 %BUILDDIR%/.. + 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 %BUILDDIR%/.. + 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" == "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/setup.rst b/docs/setup.rst new file mode 100644 index 0000000..c2ff096 --- /dev/null +++ b/docs/setup.rst @@ -0,0 +1,22 @@ +===== +Setup +===== + +Installation +============ + +Install from PyPI with ``pip``:: + + pip install django-model-utils + +To use ``django-model-utils`` in your Django project, just import and +use the utility classes described in this documentation; there is no need to +modify your ``INSTALLED_APPS`` setting. + +Dependencies +============ + +``django-model-utils`` supports `Django`_ 1.4.2 and later on Python 2.6, 2.7, +3.2, and 3.3. + +.. _Django: http://www.djangoproject.com/ diff --git a/docs/usage.rst b/docs/usage.rst new file mode 100644 index 0000000..f358ce9 --- /dev/null +++ b/docs/usage.rst @@ -0,0 +1,508 @@ +===== +Usage +===== + +Fields +====== + +Choices +------- + +``Choices`` provides some conveniences for setting ``choices`` on a Django model field: + +.. code-block:: python + + from model_utils import Choices + + class Article(models.Model): + STATUS = Choices('draft', 'published') + # ... + status = models.CharField(choices=STATUS, default=STATUS.draft, max_length=20) + +A ``Choices`` object is initialized with any number of choices. In the +simplest case, each choice is a string; that string will be used both +as the database representation of the choice, and the human-readable +representation. Note that you can access options as attributes on the +``Choices`` object: ``STATUS.draft``. + +But you may want your human-readable versions translated, in which +case you need to separate the human-readable version from the DB +representation. In this case you can provide choices as two-tuples: + +.. code-block:: python + + from model_utils import Choices + + class Article(models.Model): + STATUS = Choices(('draft', _('draft')), ('published', _('published'))) + # ... + status = models.CharField(choices=STATUS, default=STATUS.draft, max_length=20) + +But what if your database representation of choices is constrained in +a way that would hinder readability of your code? For instance, you +may need to use an ``IntegerField`` rather than a ``CharField``, or +you may want the database to order the values in your field in some +specific way. In this case, you can provide your choices as triples, +where the first element is the database representation, the second is +a valid Python identifier you will use in your code as a constant, and +the third is the human-readable version: + +.. code-block:: python + + from model_utils import Choices + + class Article(models.Model): + STATUS = Choices((0, 'draft', _('draft')), (1, 'published', _('published'))) + # ... + status = models.IntegerField(choices=STATUS, default=STATUS.draft) + + +StatusField +----------- + +A simple convenience for giving a model a set of "states." +``StatusField`` is a ``CharField`` subclass that expects to find a +``STATUS`` class attribute on its model, and uses that as its +``choices``. Also sets a default ``max_length`` of 100, and sets its +default value to the first item in the ``STATUS`` choices: + +.. code-block:: python + + from model_utils.fields import StatusField + from model_utils import Choices + + class Article(models.Model): + STATUS = Choices('draft', 'published') + # ... + status = StatusField() + +(The ``STATUS`` class attribute does not have to be a `Choices`_ +instance, it can be an ordinary list of two-tuples). + +``StatusField`` does not set ``db_index=True`` automatically; if you +expect to frequently filter on your status field (and it will have +enough selectivity to make an index worthwhile) you may want to add this +yourself. + + +MonitorField +------------ + +A ``DateTimeField`` subclass that monitors another field on the model, +and updates itself to the current date-time whenever the monitored +field changes: + +.. code-block:: python + + from model_utils.fields import MonitorField, StatusField + + class Article(models.Model): + STATUS = Choices('draft', 'published') + + status = StatusField() + status_changed = MonitorField(monitor='status') + +(A ``MonitorField`` can monitor any type of field for changes, not only a +``StatusField``.) + +SplitField +---------- + +A ``TextField`` subclass that automatically pulls an excerpt out of +its content (based on a "split here" marker or a default number of +initial paragraphs) and stores both its content and excerpt values in +the database. + +A ``SplitField`` is easy to add to any model definition: + +.. code-block:: python + + from django.db import models + from model_utils.fields import SplitField + + class Article(models.Model): + title = models.CharField(max_length=100) + body = SplitField() + +``SplitField`` automatically creates an extra non-editable field +``_body_excerpt`` to store the excerpt. This field doesn't need to be +accessed directly; see below. + +Accessing a SplitField on a model +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +When accessing an attribute of a model that was declared as a +``SplitField``, a ``SplitText`` object is returned. The ``SplitText`` +object has three attributes: + +``content``: + The full field contents. +``excerpt``: + The excerpt of ``content`` (read-only). +``has_more``: + True if the excerpt and content are different, False otherwise. + +This object also has a ``__unicode__`` method that returns the full +content, allowing ``SplitField`` attributes to appear in templates +without having to access ``content`` directly. + +Assuming the ``Article`` model above: + +.. code-block:: pycon + + >>> a = Article.objects.all()[0] + >>> a.body.content + u'some text\n\n\n\nmore text' + >>> a.body.excerpt + u'some text\n' + >>> unicode(a.body) + u'some text\n\n\n\nmore text' + +Assignment to ``a.body`` is equivalent to assignment to +``a.body.content``. + +.. note:: + + a.body.excerpt is only updated when a.save() is called + + +Customized excerpting +~~~~~~~~~~~~~~~~~~~~~ + +By default, ``SplitField`` looks for the marker ```` +alone on a line and takes everything before that marker as the +excerpt. This marker can be customized by setting the ``SPLIT_MARKER`` +setting. + +If no marker is found in the content, the first two paragraphs (where +paragraphs are blocks of text separated by a blank line) are taken to +be the excerpt. This number can be customized by setting the +``SPLIT_DEFAULT_PARAGRAPHS`` setting. + +Models +====== + +TimeFramedModel +--------------- + +An abstract base class for any model that expresses a time-range. Adds +``start`` and ``end`` nullable DateTimeFields, and a ``timeframed`` +manager that returns only objects for whom the current date-time lies +within their time range. + +StatusModel +----------- + +Pulls together `StatusField`_, `MonitorField`_ and `QueryManager`_ +into an abstract base class for any model with a "status." + +Just provide a ``STATUS`` class-attribute (a `Choices`_ object or a +list of two-tuples), and your model will have a ``status`` field with +those choices, a ``status_changed`` field containing the date-time the +``status`` was last changed, and a manager for each status that +returns objects with that status only: + +.. code-block:: python + + from model_utils.models import StatusModel + from model_utils import Choices + + class Article(StatusModel): + STATUS = Choices('draft', 'published') + + # ... + + a = Article() + a.status = Article.STATUS.published + + # this save will update a.status_changed + a.save() + + # this query will only return published articles: + Article.published.all() + +Model Managers +============== + +InheritanceManager +------------------ + +This manager (`contributed by Jeff Elmore`_) should be attached to a base model +class in a model-inheritance tree. It allows queries on that base model to +return heterogenous results of the actual proper subtypes, without any +additional queries. + +For instance, if you have a ``Place`` model with subclasses ``Restaurant`` and +``Bar``, you may want to query all Places: + +.. code-block:: python + + nearby_places = Place.objects.filter(location='here') + +But when you iterate over ``nearby_places``, you'll get only ``Place`` +instances back, even for objects that are "really" ``Restaurant`` or ``Bar``. +If you attach an ``InheritanceManager`` to ``Place``, you can just call the +``select_subclasses()`` method on the ``InheritanceManager`` or any +``QuerySet`` from it, and the resulting objects will be instances of +``Restaurant`` or ``Bar``: + +.. code-block:: python + + from model_utils.managers import InheritanceManager + + class Place(models.Model): + # ... + objects = InheritanceManager() + + class Restaurant(Place): + # ... + + class Bar(Place): + # ... + + nearby_places = Place.objects.filter(location='here').select_subclasses() + for place in nearby_places: + # "place" will automatically be an instance of Place, Restaurant, or Bar + +The database query performed will have an extra join for each subclass; if you +want to reduce the number of joins and you only need particular subclasses to +be returned as their actual type, you can pass subclass names to +``select_subclasses()``, much like the built-in ``select_related()`` method: + +.. code-block:: python + + nearby_places = Place.objects.select_subclasses("restaurant") + # restaurants will be Restaurant instances, bars will still be Place instances + +``InheritanceManager`` also provides a subclass-fetching alternative to the +``get()`` method: + +.. code-block:: python + + place = Place.objects.get_subclass(id=some_id) + # "place" will automatically be an instance of Place, Restaurant, or Bar + +If you don't explicitly call ``select_subclasses()`` or ``get_subclass()``, +an ``InheritanceManager`` behaves identically to a normal ``Manager``; so +it's safe to use as your default manager for the model. + +.. note:: + + Due to `Django bug #16572`_, on Django versions prior to 1.6 + ``InheritanceManager`` only supports a single level of model inheritance; + it won't work for grandchild models. + +.. _contributed by Jeff Elmore: http://jeffelmore.org/2010/11/11/automatic-downcasting-of-inherited-models-in-django/ +.. _Django bug #16572: https://code.djangoproject.com/ticket/16572 + + +TimeStampedModel +---------------- + +This abstract base class just provides self-updating ``created`` and +``modified`` fields on any model that inherits from it. + +QueryManager +------------ + +Many custom model managers do nothing more than return a QuerySet that +is filtered in some way. ``QueryManager`` allows you to express this +pattern with a minimum of boilerplate: + +.. code-block:: python + + from django.db import models + from model_utils.managers import QueryManager + + class Post(models.Model): + ... + published = models.BooleanField() + pub_date = models.DateField() + ... + + objects = models.Manager() + public = QueryManager(published=True).order_by('-pub_date') + +The kwargs passed to ``QueryManager`` will be passed as-is to the +``QuerySet.filter()`` method. You can also pass a ``Q`` object to +``QueryManager`` to express more complex conditions. Note that you can +set the ordering of the ``QuerySet`` returned by the ``QueryManager`` +by chaining a call to ``.order_by()`` on the ``QueryManager`` (this is +not required). + + +PassThroughManager +------------------ + +A common "gotcha" when defining methods on a custom manager class is that those +same methods are not automatically also available on the QuerySets returned by +that manager, so are not "chainable". This can be counterintuitive, as most of +the public QuerySet API is mirrored on managers. It is possible to create a +custom Manager that returns QuerySets that have the same additional methods, +but this requires boilerplate code. The ``PassThroughManager`` class +(`contributed by Paul McLanahan`_) removes this boilerplate. + +.. _contributed by Paul McLanahan: http://paulm.us/post/3717466639/passthroughmanager-for-django + +To use ``PassThroughManager``, rather than defining a custom manager with +additional methods, define a custom ``QuerySet`` subclass with the additional +methods you want, and pass that ``QuerySet`` subclass to the +``PassThroughManager.for_queryset_class()`` class method. The returned +``PassThroughManager`` subclass will always return instances of your custom +``QuerySet``, and you can also call methods of your custom ``QuerySet`` +directly on the manager: + +.. code-block:: python + + from datetime import datetime + from django.db import models + from django.db.models.query import QuerySet + from model_utils.managers import PassThroughManager + + class PostQuerySet(QuerySet): + def by_author(self, user): + return self.filter(user=user) + + def published(self): + return self.filter(published__lte=datetime.now()) + + def unpublished(self): + return self.filter(published__gte=datetime.now()) + + + class Post(models.Model): + user = models.ForeignKey(User) + published = models.DateTimeField() + + objects = PassThroughManager.for_queryset_class(PostQuerySet)() + + Post.objects.published() + Post.objects.by_author(user=request.user).unpublished() + + +Field Tracker +============= + +A ``FieldTracker`` can be added to a model to track changes in model fields. A +``FieldTracker`` allows querying for field changes since a model instance was +last saved. An example of applying ``FieldTracker`` to a model: + +.. code-block:: python + + from django.db import models + from model_utils import FieldTracker + + class Post(models.Model): + title = models.CharField(max_length=100) + body = models.TextField() + + tracker = FieldTracker() + +.. note:: + + ``django-model-utils`` 1.3.0 introduced the ``ModelTracker`` object for + tracking changes to model field values. Unfortunately ``ModelTracker`` + suffered from some serious flaws in its handling of ``ForeignKey`` fields, + potentially resulting in many extra database queries if a ``ForeignKey`` + field was tracked. In order to avoid breaking API backwards-compatibility, + ``ModelTracker`` retains the previous behavior but is deprecated, and + ``FieldTracker`` has been introduced to provide better ``ForeignKey`` + handling. All uses of ``ModelTracker`` should be replaced by + ``FieldTracker``. + + Summary of differences between ``ModelTracker`` and ``FieldTracker``: + + * The previous value returned for a tracked ``ForeignKey`` field will now + be the raw ID rather than the full object (avoiding extra database + queries). (GH-43) + + * The ``changed()`` method no longer returns the empty dictionary for all + unsaved instances; rather, ``None`` is considered to be the initial value + of all fields if the model has never been saved, thus ``changed()`` on an + unsaved instance will return a dictionary containing all fields whose + current value is not ``None``. + + * The ``has_changed()`` method no longer crashes after an object's first + save. (GH-53). + + +Accessing a field tracker +------------------------- + +There are multiple methods available for checking for changes in model fields. + + +previous +~~~~~~~~ +Returns the value of the given field during the last save: + +.. code-block:: pycon + + >>> a = Post.objects.create(title='First Post') + >>> a.title = 'Welcome' + >>> a.tracker.previous('title') + u'First Post' + +Returns ``None`` when the model instance isn't saved yet. + + +has_changed +~~~~~~~~~~~ +Returns ``True`` if the given field has changed since the last save: + +.. code-block:: pycon + + >>> a = Post.objects.create(title='First Post') + >>> a.title = 'Welcome' + >>> a.tracker.has_changed('title') + True + >>> a.tracker.has_changed('body') + False + +The ``has_changed`` method relies on ``previous`` to determine whether a +field's values has changed. + + +changed +~~~~~~~ +Returns a dictionary of all fields that have been changed since the last save +and the values of the fields during the last save: + +.. code-block:: pycon + + >>> a = Post.objects.create(title='First Post') + >>> a.title = 'Welcome' + >>> a.body = 'First post!' + >>> a.tracker.changed() + {'title': 'First Post', 'body': ''} + +The ``changed`` method relies on ``has_changed`` to determine which fields +have changed. + + +Tracking specific fields +------------------------ + +A fields parameter can be given to ``FieldTracker`` to limit tracking to +specific fields: + +.. code-block:: python + + from django.db import models + from model_utils import FieldTracker + + class Post(models.Model): + title = models.CharField(max_length=100) + body = models.TextField() + + title_tracker = FieldTracker(fields=['title']) + +An example using the model specified above: + +.. code-block:: pycon + + >>> a = Post.objects.create(title='First Post') + >>> a.body = 'First post!' + >>> a.title_tracker.changed() + {'title': None} +