├── .gitignore ├── LICENSE ├── Makefile ├── README.rst ├── conftest.py ├── docs ├── Makefile ├── conf.py ├── index.rst └── make.bat ├── index.rst ├── multiform ├── __init__.py └── forms.py ├── requirements_dev.txt ├── setup.py └── tests ├── __init__.py ├── forms.py ├── models.py ├── settings.py └── test_multiform.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | __pycache__ 3 | htmlcov 4 | .coverage 5 | env* 6 | django 7 | docs/_build 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2013 Baptiste Mispelon 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of 4 | this software and associated documentation files (the "Software"), to deal in 5 | the Software without restriction, including without limitation the rights to 6 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 7 | of the Software, and to permit persons to whom the Software is furnished to do 8 | so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | SOFTWARE. 20 | 21 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | all: test 2 | 3 | test: 4 | django-admin.py test --pythonpath=./ --settings=tests.settings 5 | flake8 multiform tests 6 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | django-multiform 2 | ================ 3 | 4 | 5 | To run the tests, use:: 6 | 7 | $ django-admin.py test --pythonpath=./ --settings=tests.settings 8 | 9 | from the project root directory. 10 | -------------------------------------------------------------------------------- /conftest.py: -------------------------------------------------------------------------------- 1 | import os 2 | from django.conf import settings 3 | 4 | 5 | def pytest_configure(): 6 | if not settings.configured: 7 | os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' 8 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | 49 | clean: 50 | rm -rf $(BUILDDIR)/* 51 | 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | dirhtml: 58 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 59 | @echo 60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 61 | 62 | singlehtml: 63 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 64 | @echo 65 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 66 | 67 | pickle: 68 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 69 | @echo 70 | @echo "Build finished; now you can process the pickle files." 71 | 72 | json: 73 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 74 | @echo 75 | @echo "Build finished; now you can process the JSON files." 76 | 77 | htmlhelp: 78 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 79 | @echo 80 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 81 | ".hhp project file in $(BUILDDIR)/htmlhelp." 82 | 83 | qthelp: 84 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 85 | @echo 86 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 87 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 88 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/django-multiform.qhcp" 89 | @echo "To view the help file:" 90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/django-multiform.qhc" 91 | 92 | devhelp: 93 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 94 | @echo 95 | @echo "Build finished." 96 | @echo "To view the help file:" 97 | @echo "# mkdir -p $$HOME/.local/share/devhelp/django-multiform" 98 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/django-multiform" 99 | @echo "# devhelp" 100 | 101 | epub: 102 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 103 | @echo 104 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 105 | 106 | latex: 107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 108 | @echo 109 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 110 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 111 | "(use \`make latexpdf' here to do that automatically)." 112 | 113 | latexpdf: 114 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 115 | @echo "Running LaTeX files through pdflatex..." 116 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 117 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 118 | 119 | latexpdfja: 120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 121 | @echo "Running LaTeX files through platex and dvipdfmx..." 122 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 123 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 124 | 125 | text: 126 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 127 | @echo 128 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 129 | 130 | man: 131 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 132 | @echo 133 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 134 | 135 | texinfo: 136 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 137 | @echo 138 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 139 | @echo "Run \`make' in that directory to run these through makeinfo" \ 140 | "(use \`make info' here to do that automatically)." 141 | 142 | info: 143 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 144 | @echo "Running Texinfo files through makeinfo..." 145 | make -C $(BUILDDIR)/texinfo info 146 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 147 | 148 | gettext: 149 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 150 | @echo 151 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 152 | 153 | changes: 154 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 155 | @echo 156 | @echo "The overview file is in $(BUILDDIR)/changes." 157 | 158 | linkcheck: 159 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 160 | @echo 161 | @echo "Link check complete; look for any errors in the above output " \ 162 | "or in $(BUILDDIR)/linkcheck/output.txt." 163 | 164 | doctest: 165 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 166 | @echo "Testing of doctests in the sources finished, look at the " \ 167 | "results in $(BUILDDIR)/doctest/output.txt." 168 | 169 | xml: 170 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 171 | @echo 172 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 173 | 174 | pseudoxml: 175 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 176 | @echo 177 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 178 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # django-multiform documentation build configuration file, created by 4 | # sphinx-quickstart on Mon Apr 1 17:58:28 2013. 5 | # 6 | # This file is execfile()d with the current directory set to its containing dir. 7 | # 8 | # Note that not all possible configuration values are present in this 9 | # autogenerated file. 10 | # 11 | # All configuration values have a default; values that are commented out 12 | # serve to show the default. 13 | 14 | import sys, os 15 | 16 | # If extensions (or modules to document with autodoc) are in another directory, 17 | # add these directories to sys.path here. If the directory is relative to the 18 | # documentation root, use os.path.abspath to make it absolute, like shown here. 19 | #sys.path.insert(0, os.path.abspath('.')) 20 | 21 | # -- General configuration ----------------------------------------------------- 22 | 23 | # If your documentation needs a minimal Sphinx version, state it here. 24 | #needs_sphinx = '1.0' 25 | 26 | # Add any Sphinx extension module names here, as strings. They can be extensions 27 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 28 | extensions = [] 29 | 30 | # Add any paths that contain templates here, relative to this directory. 31 | templates_path = ['_templates'] 32 | 33 | # The suffix of source filenames. 34 | source_suffix = '.rst' 35 | 36 | # The encoding of source files. 37 | #source_encoding = 'utf-8-sig' 38 | 39 | # The master toctree document. 40 | master_doc = 'index' 41 | 42 | # General information about the project. 43 | project = u'django-multiform' 44 | copyright = u'2013, Baptiste Mispelon' 45 | 46 | # The version info for the project you're documenting, acts as replacement for 47 | # |version| and |release|, also used in various other places throughout the 48 | # built documents. 49 | # 50 | # The short X.Y version. 51 | version = '0.1' 52 | # The full version, including alpha/beta/rc tags. 53 | release = '0.1a1' 54 | 55 | # The language for content autogenerated by Sphinx. Refer to documentation 56 | # for a list of supported languages. 57 | #language = None 58 | 59 | # There are two options for replacing |today|: either, you set today to some 60 | # non-false value, then it is used: 61 | #today = '' 62 | # Else, today_fmt is used as the format for a strftime call. 63 | #today_fmt = '%B %d, %Y' 64 | 65 | # List of patterns, relative to source directory, that match files and 66 | # directories to ignore when looking for source files. 67 | exclude_patterns = ['_build'] 68 | 69 | # The reST default role (used for this markup: `text`) to use for all documents. 70 | #default_role = None 71 | 72 | # If true, '()' will be appended to :func: etc. cross-reference text. 73 | #add_function_parentheses = True 74 | 75 | # If true, the current module name will be prepended to all description 76 | # unit titles (such as .. function::). 77 | #add_module_names = True 78 | 79 | # If true, sectionauthor and moduleauthor directives will be shown in the 80 | # output. They are ignored by default. 81 | #show_authors = False 82 | 83 | # The name of the Pygments (syntax highlighting) style to use. 84 | pygments_style = 'sphinx' 85 | 86 | # A list of ignored prefixes for module index sorting. 87 | #modindex_common_prefix = [] 88 | 89 | # If true, keep warnings as "system message" paragraphs in the built documents. 90 | #keep_warnings = False 91 | 92 | 93 | # -- Options for HTML output --------------------------------------------------- 94 | 95 | # The theme to use for HTML and HTML Help pages. See the documentation for 96 | # a list of builtin themes. 97 | html_theme = 'default' 98 | 99 | # Theme options are theme-specific and customize the look and feel of a theme 100 | # further. For a list of options available for each theme, see the 101 | # documentation. 102 | #html_theme_options = {} 103 | 104 | # Add any paths that contain custom themes here, relative to this directory. 105 | #html_theme_path = [] 106 | 107 | # The name for this set of Sphinx documents. If None, it defaults to 108 | # " v documentation". 109 | #html_title = None 110 | 111 | # A shorter title for the navigation bar. Default is the same as html_title. 112 | #html_short_title = None 113 | 114 | # The name of an image file (relative to this directory) to place at the top 115 | # of the sidebar. 116 | #html_logo = None 117 | 118 | # The name of an image file (within the static path) to use as favicon of the 119 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 120 | # pixels large. 121 | #html_favicon = None 122 | 123 | # Add any paths that contain custom static files (such as style sheets) here, 124 | # relative to this directory. They are copied after the builtin static files, 125 | # so a file named "default.css" will overwrite the builtin "default.css". 126 | html_static_path = ['_static'] 127 | 128 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 129 | # using the given strftime format. 130 | #html_last_updated_fmt = '%b %d, %Y' 131 | 132 | # If true, SmartyPants will be used to convert quotes and dashes to 133 | # typographically correct entities. 134 | #html_use_smartypants = True 135 | 136 | # Custom sidebar templates, maps document names to template names. 137 | #html_sidebars = {} 138 | 139 | # Additional templates that should be rendered to pages, maps page names to 140 | # template names. 141 | #html_additional_pages = {} 142 | 143 | # If false, no module index is generated. 144 | #html_domain_indices = True 145 | 146 | # If false, no index is generated. 147 | #html_use_index = True 148 | 149 | # If true, the index is split into individual pages for each letter. 150 | #html_split_index = False 151 | 152 | # If true, links to the reST sources are added to the pages. 153 | #html_show_sourcelink = True 154 | 155 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 156 | #html_show_sphinx = True 157 | 158 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 159 | #html_show_copyright = True 160 | 161 | # If true, an OpenSearch description file will be output, and all pages will 162 | # contain a tag referring to it. The value of this option must be the 163 | # base URL from which the finished HTML is served. 164 | #html_use_opensearch = '' 165 | 166 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 167 | #html_file_suffix = None 168 | 169 | # Output file base name for HTML help builder. 170 | htmlhelp_basename = 'django-multiformdoc' 171 | 172 | 173 | # -- Options for LaTeX output -------------------------------------------------- 174 | 175 | latex_elements = { 176 | # The paper size ('letterpaper' or 'a4paper'). 177 | #'papersize': 'letterpaper', 178 | 179 | # The font size ('10pt', '11pt' or '12pt'). 180 | #'pointsize': '10pt', 181 | 182 | # Additional stuff for the LaTeX preamble. 183 | #'preamble': '', 184 | } 185 | 186 | # Grouping the document tree into LaTeX files. List of tuples 187 | # (source start file, target name, title, author, documentclass [howto/manual]). 188 | latex_documents = [ 189 | ('index', 'django-multiform.tex', u'django-multiform Documentation', 190 | u'Baptiste Mispelon', 'manual'), 191 | ] 192 | 193 | # The name of an image file (relative to this directory) to place at the top of 194 | # the title page. 195 | #latex_logo = None 196 | 197 | # For "manual" documents, if this is true, then toplevel headings are parts, 198 | # not chapters. 199 | #latex_use_parts = False 200 | 201 | # If true, show page references after internal links. 202 | #latex_show_pagerefs = False 203 | 204 | # If true, show URL addresses after external links. 205 | #latex_show_urls = False 206 | 207 | # Documents to append as an appendix to all manuals. 208 | #latex_appendices = [] 209 | 210 | # If false, no module index is generated. 211 | #latex_domain_indices = True 212 | 213 | 214 | # -- Options for manual page output -------------------------------------------- 215 | 216 | # One entry per manual page. List of tuples 217 | # (source start file, name, description, authors, manual section). 218 | man_pages = [ 219 | ('index', 'django-multiform', u'django-multiform Documentation', 220 | [u'Baptiste Mispelon'], 1) 221 | ] 222 | 223 | # If true, show URL addresses after external links. 224 | #man_show_urls = False 225 | 226 | 227 | # -- Options for Texinfo output ------------------------------------------------ 228 | 229 | # Grouping the document tree into Texinfo files. List of tuples 230 | # (source start file, target name, title, author, 231 | # dir menu entry, description, category) 232 | texinfo_documents = [ 233 | ('index', 'django-multiform', u'django-multiform Documentation', 234 | u'Baptiste Mispelon', 'django-multiform', 'One line description of project.', 235 | 'Miscellaneous'), 236 | ] 237 | 238 | # Documents to append as an appendix to all manuals. 239 | #texinfo_appendices = [] 240 | 241 | # If false, no module index is generated. 242 | #texinfo_domain_indices = True 243 | 244 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 245 | #texinfo_show_urls = 'footnote' 246 | 247 | # If true, do not generate a @detailmenu in the "Top" node's menu. 248 | #texinfo_no_detailmenu = False 249 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. django-multiform documentation master file, created by 2 | sphinx-quickstart on Mon Apr 1 17:58:28 2013. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to django-multiform's documentation! 7 | ============================================ 8 | 9 | Django-multiform is a library that allows you to wrap several forms 10 | into one object with a form-like API. 11 | 12 | It's compatible with django 1.4 and 1.5. 13 | 14 | A lot of care has been put into replicating the same API as Form so that a 15 | MultiForm can be used anywhere a regular Form would. 16 | 17 | The library consists of two classes: ``MultiForm`` and ``MultiModelForm``. 18 | 19 | 20 | MultiForm 21 | --------- 22 | 23 | Wraps up several ``Form`` into one object, which allows you for example 24 | to reuse several existing forms in a generic ``FormView``. 25 | 26 | .. sourcecode:: python 27 | 28 | # forms.py 29 | from django import forms 30 | 31 | from multiform import MultiForm 32 | 33 | class FooForm(forms.Form): 34 | foo = forms.CharField() 35 | 36 | class BarForm(forms.Form): 37 | bar = forms.CharField() 38 | 39 | class FooBarForm(MultiForm): 40 | base_forms = [ 41 | ('foo', FooForm), 42 | ('bar', BarForm), 43 | ] 44 | 45 | # views.py 46 | from django.views import generic 47 | from .forms import FooBarForm 48 | 49 | class FooBarView(generic.FormView): 50 | form_class = FooBarForm 51 | 52 | def form_valid(self, form): 53 | form.cleaned_data['foo'] # {'foo': ...} 54 | form.cleaned_data['bar'] # {'bar': ...} 55 | return super(FooBarView, self).form_valid(form) 56 | 57 | 58 | MultiModelForm 59 | -------------- 60 | 61 | As the name hints, it wraps several ``ModelForm`` instances into one object. 62 | 63 | It's quite similar to ``MultiForm``, but it adds a ``save`` method and it can 64 | handle the dispatching of the ``instance`` attribute that you usually 65 | pass to a ``ModelForm``. 66 | 67 | It's useful for creating related model instances in one step with a generic 68 | CreateView for example. 69 | 70 | .. sourcecode:: python 71 | 72 | # models.py 73 | from django.db import models 74 | 75 | class Person(models.Model): 76 | eye_color = models.CharField(max_length=50) 77 | user = models.OneToOneField(auth.get_user_model()) 78 | 79 | # forms.py 80 | from django.contrib.auth.forms import UserCreationForm 81 | from .models import Person 82 | 83 | from multiform import MultiModelForm 84 | 85 | class PersonUserForm(MultiModelForm): 86 | base_forms = [ 87 | ('person', PersonForm), 88 | ('user', UserCreationForm), 89 | ] 90 | 91 | def dispatch_init_instance(self, name, instance): 92 | if name == 'person': 93 | return instance 94 | return super(PersonUserForm, self).dispatch_init_instance(name, instance) 95 | 96 | def save(self, commit=True): 97 | """Save both forms and attach the user to the person.""" 98 | instances = super(PersonUserForm, self).save(commit=False) 99 | instances['person'].user = instances['user'] 100 | if commit: 101 | for instance in instances.values(): 102 | instance.save() 103 | return instances 104 | 105 | 106 | Dispatching Parameters 107 | ---------------------- 108 | 109 | In the event that you want to pass different parameters to some of the wrapped 110 | forms, you have two options (that can be used independently): 111 | 112 | 1) Implement a ``dispatch_init_$arg`` method on your subclass. 113 | This method will be called when builting the keyword arguments passed to 114 | a wrapped form's constructor. 115 | This method is passed two arguments: the name of the wrapped form being built, 116 | and the original value of the $arg keyword argument. 117 | 118 | 2) Pass a ``$name__$arg=foo`` keyword argument to the MultiForm's constructor. 119 | This will make it so that the wrapped form with the name of ``$name`` will be 120 | passed the ``$arg=foo`` keyword argument. 121 | Note that in case of conflicts, this method has priority over the first one. 122 | 123 | 124 | Any keyword argument passed to a Multiform's contructor that's not part of 125 | the Form's signature and that's not of the form ``$name__*`` will be passed to 126 | all wrapped forms. 127 | 128 | 129 | 130 | Indices and tables 131 | ================== 132 | 133 | * :ref:`genindex` 134 | * :ref:`modindex` 135 | * :ref:`search` 136 | 137 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 31 | echo. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. xml to make Docutils-native XML files 37 | echo. pseudoxml to make pseudoxml-XML files for display purposes 38 | echo. linkcheck to check all external links for integrity 39 | echo. doctest to run all doctests embedded in the documentation if enabled 40 | goto end 41 | ) 42 | 43 | if "%1" == "clean" ( 44 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 45 | del /q /s %BUILDDIR%\* 46 | goto end 47 | ) 48 | 49 | 50 | %SPHINXBUILD% 2> nul 51 | if errorlevel 9009 ( 52 | echo. 53 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 54 | echo.installed, then set the SPHINXBUILD environment variable to point 55 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 56 | echo.may add the Sphinx directory to PATH. 57 | echo. 58 | echo.If you don't have Sphinx installed, grab it from 59 | echo.http://sphinx-doc.org/ 60 | exit /b 1 61 | ) 62 | 63 | if "%1" == "html" ( 64 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 65 | if errorlevel 1 exit /b 1 66 | echo. 67 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 68 | goto end 69 | ) 70 | 71 | if "%1" == "dirhtml" ( 72 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 73 | if errorlevel 1 exit /b 1 74 | echo. 75 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 76 | goto end 77 | ) 78 | 79 | if "%1" == "singlehtml" ( 80 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 81 | if errorlevel 1 exit /b 1 82 | echo. 83 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 84 | goto end 85 | ) 86 | 87 | if "%1" == "pickle" ( 88 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 89 | if errorlevel 1 exit /b 1 90 | echo. 91 | echo.Build finished; now you can process the pickle files. 92 | goto end 93 | ) 94 | 95 | if "%1" == "json" ( 96 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 97 | if errorlevel 1 exit /b 1 98 | echo. 99 | echo.Build finished; now you can process the JSON files. 100 | goto end 101 | ) 102 | 103 | if "%1" == "htmlhelp" ( 104 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 105 | if errorlevel 1 exit /b 1 106 | echo. 107 | echo.Build finished; now you can run HTML Help Workshop with the ^ 108 | .hhp project file in %BUILDDIR%/htmlhelp. 109 | goto end 110 | ) 111 | 112 | if "%1" == "qthelp" ( 113 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 114 | if errorlevel 1 exit /b 1 115 | echo. 116 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 117 | .qhcp project file in %BUILDDIR%/qthelp, like this: 118 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\django-multiform.qhcp 119 | echo.To view the help file: 120 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\django-multiform.ghc 121 | goto end 122 | ) 123 | 124 | if "%1" == "devhelp" ( 125 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished. 129 | goto end 130 | ) 131 | 132 | if "%1" == "epub" ( 133 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 134 | if errorlevel 1 exit /b 1 135 | echo. 136 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 137 | goto end 138 | ) 139 | 140 | if "%1" == "latex" ( 141 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 142 | if errorlevel 1 exit /b 1 143 | echo. 144 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 145 | goto end 146 | ) 147 | 148 | if "%1" == "latexpdf" ( 149 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 150 | cd %BUILDDIR%/latex 151 | make all-pdf 152 | cd %BUILDDIR%/.. 153 | echo. 154 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 155 | goto end 156 | ) 157 | 158 | if "%1" == "latexpdfja" ( 159 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 160 | cd %BUILDDIR%/latex 161 | make all-pdf-ja 162 | cd %BUILDDIR%/.. 163 | echo. 164 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 165 | goto end 166 | ) 167 | 168 | if "%1" == "text" ( 169 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 170 | if errorlevel 1 exit /b 1 171 | echo. 172 | echo.Build finished. The text files are in %BUILDDIR%/text. 173 | goto end 174 | ) 175 | 176 | if "%1" == "man" ( 177 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 178 | if errorlevel 1 exit /b 1 179 | echo. 180 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 181 | goto end 182 | ) 183 | 184 | if "%1" == "texinfo" ( 185 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 186 | if errorlevel 1 exit /b 1 187 | echo. 188 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 189 | goto end 190 | ) 191 | 192 | if "%1" == "gettext" ( 193 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 194 | if errorlevel 1 exit /b 1 195 | echo. 196 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 197 | goto end 198 | ) 199 | 200 | if "%1" == "changes" ( 201 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 202 | if errorlevel 1 exit /b 1 203 | echo. 204 | echo.The overview file is in %BUILDDIR%/changes. 205 | goto end 206 | ) 207 | 208 | if "%1" == "linkcheck" ( 209 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 210 | if errorlevel 1 exit /b 1 211 | echo. 212 | echo.Link check complete; look for any errors in the above output ^ 213 | or in %BUILDDIR%/linkcheck/output.txt. 214 | goto end 215 | ) 216 | 217 | if "%1" == "doctest" ( 218 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 219 | if errorlevel 1 exit /b 1 220 | echo. 221 | echo.Testing of doctests in the sources finished, look at the ^ 222 | results in %BUILDDIR%/doctest/output.txt. 223 | goto end 224 | ) 225 | 226 | if "%1" == "xml" ( 227 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 228 | if errorlevel 1 exit /b 1 229 | echo. 230 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 231 | goto end 232 | ) 233 | 234 | if "%1" == "pseudoxml" ( 235 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 236 | if errorlevel 1 exit /b 1 237 | echo. 238 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 239 | goto end 240 | ) 241 | 242 | :end 243 | -------------------------------------------------------------------------------- /index.rst: -------------------------------------------------------------------------------- 1 | django-multiform 2 | ================ 3 | 4 | Django-multiform is a library that allows you to wrap several forms 5 | into one object with a form-like API. 6 | 7 | This allows you for example to use a generic view like CreateView to 8 | create several different types of models at once. 9 | 10 | 11 | .. sourcecode:: python 12 | 13 | # forms.py 14 | from django import forms 15 | 16 | class FooForm(forms.Form): 17 | foo = forms.CharField() 18 | 19 | class BarForm(forms.Form): 20 | bar = forms.CharField() 21 | 22 | class FooBarForm(MultiForm): 23 | base_forms = [ 24 | ('foo', FooForm), 25 | ('bar', BarForm), 26 | ] 27 | 28 | # views.py 29 | from django.views import generic 30 | from .forms import FooBarForm 31 | 32 | class FooBarView(generic.FormView): 33 | form_class = FooBarForm 34 | 35 | def form_valid(self, form): 36 | form.cleaned_data['foo'] # {'foo': ...} 37 | form.cleaned_data['bar'] # {'bar': ...} 38 | return super(FooBarView, self).form_valid(form) 39 | 40 | 41 | .. sourcecode:: python 42 | 43 | # models.py 44 | from django.db import models 45 | 46 | class Person(models.Model): 47 | eye_color = models.CharField(max_length=50) 48 | user = models.OneToOneField(auth.get_user_model()) 49 | 50 | # forms.py 51 | from django.contrib.auth.forms import UserCreationForm 52 | from .models import Person 53 | 54 | class PersonUserForm(MultiModelForm): 55 | base_forms = [ 56 | ('person', PersonForm), 57 | ('user', UserCreationForm), 58 | ] 59 | 60 | def dispatch_init_instance(self, name, instance): 61 | if name == 'person': 62 | return instance 63 | return super(PersonUserForm, self).dispatch_init_instance(name, instance) 64 | 65 | def save(self, commit=True): 66 | """Save both forms and attach the user to the person.""" 67 | instances = super(PersonUserForm, self).save(commit=False) 68 | instances['person'].user = instances['user'] 69 | if commit: 70 | for instance in instances.values(): 71 | instance.save() 72 | return instances 73 | 74 | 75 | A lot of care has been put into replicating the same API as Form so that a 76 | MultiForm can be used anywhere a regular Form would. 77 | 78 | In the event that you want to pass different parameters to some of the wrapped 79 | forms, you have two options (that can be used independently): 80 | 81 | 1) Implement a ``dispatch_init_$arg`` method on your subclass. 82 | This method will be called when builting the keyword arguments passed to 83 | a wrapped form's constructor. 84 | This method is passed two arguments: the name of the wrapped form being built, 85 | and the original value of the $arg keyword argument. 86 | 87 | 2) Pass a ``$name__$arg=foo`` keyword argument to the MultiForm's constructor. 88 | This will make it so that the wrapped form with the name of ``$name`` will be 89 | passed the ``$arg=foo`` keyword argument. 90 | Note that in case of conflicts, this method has priority over the first one. 91 | 92 | 93 | Any keyword argument passed to a Multiform's contructor that's not part of 94 | the Form's signature and that's not of the form ``$name__*`` will be passed to 95 | all wrapped forms. 96 | -------------------------------------------------------------------------------- /multiform/__init__.py: -------------------------------------------------------------------------------- 1 | from .forms import MultiForm, MultiModelForm, InvalidArgument # noqa 2 | -------------------------------------------------------------------------------- /multiform/forms.py: -------------------------------------------------------------------------------- 1 | from __future__ import unicode_literals 2 | 3 | from collections import defaultdict, OrderedDict 4 | from itertools import chain 5 | from functools import reduce 6 | 7 | import operator 8 | 9 | from django.core.exceptions import ImproperlyConfigured 10 | from django.forms.forms import BaseForm 11 | from django.forms.util import ErrorList 12 | from django.forms.widgets import Media 13 | from django.utils.safestring import mark_safe 14 | 15 | 16 | class InvalidArgument: 17 | pass 18 | 19 | 20 | class MultiForm(BaseForm): 21 | """ 22 | A BaseForm subclass that can wrap several sub-forms into one entity. 23 | To use it, define a `base_forms` attribute which should be a mapping 24 | (dict or collections.OrderedDict for example). 25 | It can then be used like a regular form. 26 | """ 27 | 28 | base_fields = None # Needed to bypass the absence of fancy metaclass 29 | _baseform_signature = OrderedDict([ # TODO: signature objects (pep 362) 30 | ('data', None), 31 | ('files', None), 32 | ('auto_id', 'id_%s'), 33 | ('prefix', None), 34 | ('initial', None), 35 | ('error_class', ErrorList), 36 | ('label_suffix', ':'), 37 | ('empty_permitted', False), 38 | ]) 39 | 40 | def __init__(self, *args, **kwargs): 41 | sig_kwargs, extra_kwargs = self._normalize_init_signature(args, kwargs) 42 | self._init_parent(**sig_kwargs) 43 | self._init_wrapped_forms(sig_kwargs, extra_kwargs) 44 | 45 | def _init_parent(self, **kwargs): 46 | super(MultiForm, self).__init__(**kwargs) 47 | 48 | def _normalize_init_signature(self, args, kwargs): 49 | """ 50 | Put all the given arguments to __init__ into a dict, whether they were 51 | passed as positional arguments or keyword ones. 52 | Return two dictionaries: the normalized init arguments and another one 53 | with the extra ones (not part of the signature). 54 | """ 55 | if len(args) > len(self._baseform_signature): 56 | msg = "%s.__init__ got too many positional arguments." 57 | raise TypeError(msg % self.__class__) 58 | 59 | normalized_kwargs = self._baseform_signature.copy() 60 | 61 | for k, v in zip(self._baseform_signature, args): 62 | if k in kwargs: 63 | msg = "%s.__init__ got multiple values for argument '%s'" 64 | raise TypeError(msg % (self.__class__, k)) 65 | normalized_kwargs[k] = v 66 | 67 | for k in list(self._baseform_signature)[len(args):]: # remaining ones 68 | try: 69 | normalized_kwargs[k] = kwargs.pop(k) 70 | except KeyError: 71 | pass 72 | 73 | # at this point, ``kwargs`` only contain keys that are not 74 | # in the form's signature 75 | return normalized_kwargs, kwargs 76 | 77 | def _init_wrapped_forms(self, sig_kwargs, extra_kwargs): 78 | """ 79 | Initialize the wrapped forms by passing the ones received in __init__ 80 | and adding the keyword arguments whose names look like `$name__*`. 81 | """ 82 | base_forms = self.get_base_forms() 83 | # We start by extracting all the keyword parameters that look like 84 | # "$name__*" where $name is the name of one of the wrapped form. 85 | # With this, we build a mapping of (name -> stripped_kwargs) 86 | # where the stripped_kwargs have been stripped off of the form's name. 87 | dispatched_kwargs = defaultdict(dict) 88 | for k in list(extra_kwargs): # Because we mutate it 89 | prefix, _, remainder = k.partition('__') 90 | if remainder and prefix in base_forms: 91 | dispatched_kwargs[prefix][remainder] = extra_kwargs.pop(k) 92 | 93 | # Any extra_kwargs left at this point will be passed as-is to all 94 | # wrapped forms. 95 | 96 | self.forms = OrderedDict() 97 | for name, form_class in base_forms.items(): 98 | # We build each wrapped form one by one. 99 | # Their keyword arguments are built in three steps, each with 100 | # precedence over the next one: 101 | # 1) For all the keywords that are part of the normal signature, 102 | # we check for the presence of a dispatch_init_$keyword method 103 | # on the instance. 104 | # If no such method is present, we just pass the value of the 105 | # argument as-is. 106 | # If such a method exists, then we use the result of calling 107 | # this method, passing the form's name and the original value. 108 | # 2) For any existing ``extra_kwargs`` we check for the presence 109 | # of a dispatch_init_$keyword method on the instance. 110 | # If no such method is present, we just pass the value of the 111 | # argument as-is. 112 | # If such a method exists, then we use the result of calling 113 | # this method, passing the form's name and the original value. 114 | # 3) If some dispatched_kwargs exist for this method (that is, 115 | # keyword arguments passed to the MultiForm's __init__ whose 116 | # name look like "$name__*"), then they are applied. 117 | kwargs = {} 118 | for k, v in chain(sig_kwargs.items(), extra_kwargs.items()): 119 | if hasattr(self, 'dispatch_init_%s' % k): 120 | v = getattr(self, 'dispatch_init_%s' % k)(name, v) 121 | if v is InvalidArgument: 122 | continue 123 | kwargs[k] = v 124 | kwargs.update(dispatched_kwargs[name]) 125 | self.forms[name] = form_class(**kwargs) 126 | 127 | def dispatch_init_prefix(self, name, prefix): 128 | """ 129 | When instanciating a wrapped form, we add its name to the given prefix. 130 | """ 131 | # prefix is already stored on self.prefix by super().__init__, 132 | # so self.add_prefix works. 133 | return self.add_prefix(name) 134 | 135 | def get_base_forms(self): 136 | """ 137 | Return a mapping of the forms that this multiform wraps (name -> form). 138 | """ 139 | if not getattr(self, 'base_forms', None): 140 | error_message_fmt = "%s does not define a base_forms attribute." 141 | raise ImproperlyConfigured(error_message_fmt % self.__class__) 142 | 143 | # Incidentally, this also makes a shallow copy 144 | return OrderedDict(self.base_forms) 145 | 146 | def _combine(self, attr, filter=False, 147 | call=False, call_args=(), call_kwargs=None, 148 | ignore_missing=False): 149 | """ 150 | Combine an attribute (or method) of each wrapped form into an 151 | OrderedDict. 152 | To remove empty vales from the dict, pass ``filer=False``. 153 | To call a method, pass ``call=True`` (passing ``call_args`` and 154 | ``call_kwargs`` if needed). 155 | """ 156 | if not call_kwargs: 157 | call_kwargs = {} 158 | d = OrderedDict() 159 | for name, form in self.forms.items(): 160 | if ignore_missing and not hasattr(form, attr): 161 | if not filter: 162 | d[name] = None 163 | continue 164 | v = getattr(form, attr) 165 | if call: 166 | v = v(*call_args, **call_kwargs) 167 | if not filter or v: 168 | d[name] = v 169 | return d 170 | 171 | def _combine_values(self, *args, **kwargs): 172 | """ 173 | Similar to _combine, but only return the values, not the full dict. 174 | """ 175 | return self._combine(*args, **kwargs).values() 176 | 177 | def _combine_chain(self, *args, **kwargs): 178 | """Use itertools.chain on the combined values.""" 179 | return chain.from_iterable(self._combine_values(*args, **kwargs)) 180 | 181 | # All BaseForm's public methods and properties are implemented next. 182 | # Basically, a call to a MultiForm's method gets dispatched to all the 183 | # wrapped forms and the results get collected either in an OrderedDict 184 | # or in a list. 185 | 186 | def __iter__(self): 187 | return chain.from_iterable(self._combine_values('__iter__', call=True)) 188 | 189 | def __getitem__(self, name): 190 | return self.forms[name] 191 | 192 | def _html_output(self, *args, **kwargs): 193 | rendered = self._combine_values('_html_output', call=True, filter=True, 194 | call_args=args, call_kwargs=kwargs) 195 | return mark_safe('\n'.join(rendered)) 196 | 197 | def non_field_errors(self): 198 | return self._combine('non_field_errors', call=True, filter=True) 199 | 200 | def full_clean(self): 201 | # This will call full_clean on all sub-forms 202 | # (and populate their _errors attribute): 203 | self._errors = self._combine('errors', filter=True) 204 | 205 | if not self._errors: 206 | # Each sub-form's cleaned_data is now populated 207 | self.cleaned_data = self._combine('cleaned_data') 208 | 209 | @property 210 | def changed_data(self): 211 | return self._combine('changed_data', filter=True) 212 | 213 | @property 214 | def media(self): 215 | return reduce(operator.add, self._combine_values('media'), Media()) 216 | 217 | def is_multipart(self): 218 | return any(self._combine_values('is_multipart', call=True)) 219 | 220 | def hidden_fields(self): 221 | return list(self._combine_chain('hidden_fields', call=True)) 222 | 223 | def visible_fields(self): 224 | return list(self._combine_chain('visible_fields', call=True)) 225 | 226 | 227 | class MultiModelForm(MultiForm): 228 | """ 229 | A MultiForm that supports a ModelForm's signature. 230 | Also implements a save method. 231 | """ 232 | _baseform_signature = OrderedDict( 233 | list(MultiForm._baseform_signature.items()) + [('instance', None)]) 234 | 235 | def _init_parent(self, **kwargs): 236 | del kwargs['instance'] 237 | super(MultiForm, self).__init__(**kwargs) 238 | 239 | def dispatch_init_instance(self, name, instance): 240 | if instance is None: 241 | return None 242 | return getattr(instance, name) 243 | 244 | def save(self, commit=True): 245 | # TODO: Find a good API to wrap this in a db transaction 246 | # TODO: allow committing some forms but not others 247 | instances = self._combine('save', call=True, 248 | call_kwargs={'commit': commit}) 249 | if commit: 250 | self.save_m2m() 251 | return instances 252 | 253 | def save_m2m(self): 254 | # TODO: Find a good API to wrap this in a db transaction 255 | return self._combine('save_m2m', filter=True, call=True, 256 | ignore_missing=True) 257 | -------------------------------------------------------------------------------- /requirements_dev.txt: -------------------------------------------------------------------------------- 1 | # For running the tests 2 | pytest-django 3 | pytest-cov 4 | 5 | # For building the documentation 6 | Sphinx==1.2b1 7 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | 3 | setup( 4 | name="django-multiform", 5 | version="0.1", 6 | description="Wrap several django forms into one form-like object", 7 | keywords="django, forms, multiform", 8 | author="Baptiste Mispelon", 9 | author_email="bmispelon@gmail.com", 10 | license="MIT", 11 | url="https://github.com/bmispelon/django-multiform", 12 | packages=find_packages(), 13 | include_package_data=True, 14 | classifiers=[ 15 | "Operating System :: OS Independent", 16 | "License :: OSI Approved :: MIT License", 17 | "Intended Audience :: Developers", 18 | "Programming Language :: Python :: 2.6", 19 | "Programming Language :: Python :: 2.7", 20 | "Programming Language :: Python :: 3.2", 21 | "Programming Language :: Python :: 3.3", 22 | ] 23 | ) 24 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bmispelon/django-multiform/0e02f0d5729a80502a290070b474f3e3ac85c926/tests/__init__.py -------------------------------------------------------------------------------- /tests/forms.py: -------------------------------------------------------------------------------- 1 | from django import forms 2 | 3 | from multiform import MultiForm, MultiModelForm, InvalidArgument 4 | 5 | from .models import Pizza, Topping 6 | 7 | 8 | class EmptyForm(forms.Form): 9 | pass 10 | 11 | 12 | class FooForm(forms.Form): 13 | foo = forms.CharField() 14 | 15 | 16 | class HiddenForm(forms.Form): 17 | bar = forms.CharField(widget=forms.HiddenInput) 18 | 19 | 20 | class MediaForm(forms.Form): 21 | class Media: 22 | js = ('tests.js',) 23 | 24 | 25 | class MultipartForm(forms.Form): 26 | file = forms.FileField(required=False) 27 | 28 | 29 | class CapturingForm(forms.Form): 30 | def __init__(self, *args, **kwargs): 31 | self.captured = kwargs.pop('capture', None) 32 | super(CapturingForm, self).__init__(*args, **kwargs) 33 | 34 | 35 | class ValidationErrorForm(forms.Form): 36 | def clean(self): 37 | raise forms.ValidationError('error') 38 | 39 | 40 | class InitialForm(forms.Form): 41 | baz = forms.CharField(initial='baz', required=False) 42 | 43 | 44 | class PizzaModelForm(forms.ModelForm): 45 | class Meta: 46 | model = Pizza 47 | fields = ('name',) 48 | 49 | 50 | class PizzaWithRestaurantModelForm(forms.ModelForm): 51 | class Meta: 52 | model = Pizza 53 | fields = ('name', 'restaurant') 54 | 55 | 56 | class ToppingModelForm(forms.ModelForm): 57 | class Meta: 58 | model = Topping 59 | fields = ('name',) 60 | 61 | 62 | SAMPLE_FORMS = [ 63 | ('empty', EmptyForm), 64 | ('capture', CapturingForm), 65 | ('media', MediaForm), 66 | ('foo', FooForm), 67 | ] 68 | 69 | 70 | class SampleMultiForm(MultiForm): 71 | base_forms = SAMPLE_FORMS 72 | 73 | 74 | class MultiFormWithHiddenFields(MultiForm): 75 | base_forms = [ 76 | ('foo', FooForm), 77 | ('hidden', HiddenForm), 78 | ] 79 | 80 | 81 | class MultiFormWithInvalidArgument(MultiForm): 82 | base_forms = [ 83 | ('foo', FooForm), 84 | ('capture', CapturingForm), 85 | ] 86 | 87 | def dispatch_init_capture(self, name, captured): 88 | if name == "capture": 89 | return captured 90 | return InvalidArgument 91 | 92 | 93 | class MultiFormWithFileInput(MultiForm): 94 | base_forms = [ 95 | ('multipart', MultipartForm), 96 | ] 97 | 98 | 99 | class MultiFormWithNonFieldError(MultiForm): 100 | base_forms = [ 101 | ('error', ValidationErrorForm) 102 | ] 103 | 104 | 105 | class MultiFormWithInitial(MultiForm): 106 | base_forms = [ 107 | ('initial', InitialForm), 108 | ] 109 | 110 | 111 | class ToppingMultiModelForm(MultiModelForm): 112 | base_forms = { 113 | 'pizza': PizzaModelForm, 114 | 'topping': ToppingModelForm, 115 | } 116 | 117 | def dispatch_init_instance(self, name, instance): 118 | if name == 'topping': 119 | return instance 120 | return super(ToppingMultiModelForm, self) \ 121 | .dispatch_init_instance(name, instance) 122 | 123 | 124 | class ToppingPizzaRestaurantMultiModelForm(MultiModelForm): 125 | base_forms = { 126 | 'pizza': PizzaWithRestaurantModelForm, 127 | 'topping': ToppingModelForm, 128 | } 129 | 130 | def dispatch_init_instance(self, name, instance): 131 | if name == 'topping': 132 | return instance 133 | return super(ToppingPizzaRestaurantMultiModelForm, self) \ 134 | .dispatch_init_instance(name, instance) 135 | -------------------------------------------------------------------------------- /tests/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | 4 | class Pizza(models.Model): 5 | name = models.CharField(max_length=50) 6 | restaurant = models.ManyToManyField('Restaurant') 7 | 8 | 9 | class Restaurant(models.Model): 10 | name = models.CharField(max_length=50) 11 | 12 | 13 | class Topping(models.Model): 14 | pizza = models.ForeignKey(Pizza) 15 | name = models.CharField(max_length=50) 16 | -------------------------------------------------------------------------------- /tests/settings.py: -------------------------------------------------------------------------------- 1 | SECRET_KEY = 'local' 2 | 3 | DATABASES = { 4 | 'default': { 5 | 'ENGINE': 'django.db.backends.sqlite3', 6 | 'NAME': ':memory:', 7 | } 8 | } 9 | 10 | INSTALLED_APPS = [ 11 | 'tests', 12 | ] 13 | -------------------------------------------------------------------------------- /tests/test_multiform.py: -------------------------------------------------------------------------------- 1 | from collections import OrderedDict 2 | 3 | from django import test 4 | from django.core.exceptions import ImproperlyConfigured 5 | 6 | from multiform import MultiForm 7 | 8 | from .forms import ( 9 | EmptyForm, 10 | SampleMultiForm, 11 | MultiFormWithHiddenFields, 12 | MultiFormWithInvalidArgument, 13 | MultiFormWithFileInput, 14 | MultiFormWithNonFieldError, 15 | MultiFormWithInitial, 16 | SAMPLE_FORMS, 17 | 18 | ToppingMultiModelForm, 19 | ToppingPizzaRestaurantMultiModelForm, 20 | ) 21 | from .models import Pizza, Restaurant, Topping 22 | 23 | 24 | def make_multiform(base_forms=None, base=MultiForm, name=""): 25 | return type(name, (base,), {'base_forms': base_forms}) 26 | 27 | 28 | class TestMultiForm(test.TestCase): 29 | 30 | def test_improperly_configured(self): 31 | """ 32 | Try to initialize a multiform subclass with empty base_forms values. 33 | """ 34 | with self.assertRaises(ImproperlyConfigured): 35 | make_multiform()() 36 | with self.assertRaises(ImproperlyConfigured): 37 | make_multiform([])() 38 | with self.assertRaises(ImproperlyConfigured): 39 | make_multiform({})() 40 | 41 | def test_init_too_many_positional_args(self): 42 | with self.assertRaises(TypeError): 43 | args = [None] * 20 44 | SampleMultiForm(*args) 45 | 46 | def test_init_duplicate_param(self): 47 | """ 48 | Check that passing an argument both as positional and named fails. 49 | """ 50 | with self.assertRaises(TypeError): 51 | # data is the first argument of the signature 52 | SampleMultiForm(None, data=None) 53 | 54 | def test_base_forms(self): 55 | """ 56 | Check that various types are accepted for the base_forms attribute. 57 | """ 58 | expected = sorted(name for name, form_class in SAMPLE_FORMS) 59 | 60 | for base_forms in [ 61 | SAMPLE_FORMS, # list of 2-tuple 62 | dict(SAMPLE_FORMS), 63 | OrderedDict(SAMPLE_FORMS) 64 | ]: 65 | form = make_multiform(base_forms)() 66 | self.assertEqual(expected, sorted(form.forms)) 67 | 68 | def test_dispatch_kwargs(self): 69 | form = SampleMultiForm() 70 | self.assertIs(None, form['capture'].captured) 71 | form = SampleMultiForm(capture__capture='hello') 72 | self.assertEquals('hello', form['capture'].captured) 73 | 74 | def test_dispatch_kwargs_not_provided(self): 75 | form = MultiFormWithInvalidArgument() 76 | self.assertIs(None, form['capture'].captured) 77 | self.assertFalse(hasattr(form['foo'], 'captured')) 78 | form = MultiFormWithInvalidArgument(capture='hello') 79 | self.assertEquals('hello', form['capture'].captured) 80 | self.assertFalse(hasattr(form['foo'], 'captured')) 81 | 82 | def test_getitem(self): 83 | form = SampleMultiForm() 84 | self.assertIsInstance(form['empty'], EmptyForm) 85 | 86 | def test_iter(self): 87 | form = SampleMultiForm() 88 | self.assertEqual([f.name for f in form], ['foo']) 89 | 90 | def test_as_ul(self): 91 | form = SampleMultiForm() 92 | expected = ('
  • ' 93 | '' 94 | '
  • ') 95 | self.assertHTMLEqual(form.as_ul().strip(), expected) 96 | 97 | def test_as_table(self): 98 | form = SampleMultiForm() 99 | expected = ('' 100 | '' 101 | '') 102 | self.assertHTMLEqual(form.as_table().strip(), expected) 103 | 104 | def test_as_p(self): 105 | form = SampleMultiForm() 106 | expected = ('

    ' 107 | '

    ') 108 | self.assertHTMLEqual(form.as_p().strip(), expected) 109 | 110 | def test_nonfield_errors(self): 111 | form = MultiFormWithNonFieldError({}) 112 | self.assertFalse(form.is_valid()) 113 | self.assertEqual(form.non_field_errors(), {'error': ['error']}) 114 | 115 | def test_is_valid(self): 116 | form = SampleMultiForm() 117 | self.assertFalse(form.is_valid()) 118 | form = SampleMultiForm({}) 119 | self.assertFalse(form.is_valid()) 120 | form = SampleMultiForm({'foo-foo': 'yes'}) 121 | self.assertTrue(form.is_valid()) 122 | 123 | def test_cleaned_data(self): 124 | form = SampleMultiForm({'foo-foo': 'yes'}) 125 | self.assertTrue(form.is_valid()) 126 | self.assertEqual(form.cleaned_data, { 127 | 'empty': {}, 128 | 'capture': {}, 129 | 'media': {}, 130 | 'foo': {'foo': 'yes'}, 131 | }) 132 | 133 | def test_changed_data(self): 134 | form = MultiFormWithInitial({'initial-baz': 'hello'}) 135 | self.assertEqual(form.changed_data, {'initial': ['baz']}) 136 | 137 | def test_media(self): 138 | form = SampleMultiForm() 139 | expected = '' 140 | self.assertHTMLEqual(str(form.media), expected) 141 | 142 | def test_multipart(self): 143 | form = SampleMultiForm() 144 | self.assertFalse(form.is_multipart()) 145 | form = MultiFormWithFileInput() 146 | self.assertTrue(form.is_multipart()) 147 | 148 | def test_hidden_fields(self): 149 | form = MultiFormWithHiddenFields() 150 | self.assertEqual([f.name for f in form.hidden_fields()], ['bar']) 151 | 152 | def test_visible_fields(self): 153 | form = MultiFormWithHiddenFields() 154 | self.assertEqual([f.name for f in form.visible_fields()], ['foo']) 155 | 156 | 157 | class TestMultiModelForm(test.TestCase): 158 | 159 | def test_dispatch_instance_none(self): 160 | """When passing instance=None, an empty object is created.""" 161 | form = ToppingMultiModelForm() 162 | self.assertIs(form['pizza'].instance.pk, None) 163 | self.assertEqual(form['pizza'].instance.name, '') 164 | self.assertIs(form['topping'].instance.pk, None) 165 | self.assertEqual(form['topping'].instance.name, '') 166 | 167 | def test_dispatch_instance(self): 168 | pizza = Pizza.objects.create(name='Plain') 169 | topping = Topping.objects.create(pizza=pizza, name='tomato sauce') 170 | form = ToppingMultiModelForm(instance=topping) 171 | self.assertEqual(form['pizza'].instance, pizza) 172 | self.assertEqual(form['topping'].instance, topping) 173 | 174 | def test_save(self): 175 | data = {'topping-name': 'tomato sauce', 'pizza-name': 'Plain'} 176 | form = ToppingMultiModelForm(data) 177 | self.assertTrue(form.is_valid()) 178 | d = form.save(commit=False) 179 | d['pizza'].save() 180 | d['topping'].pizza = d['pizza'] 181 | d['topping'].save() 182 | self.assertEqual(d['topping'], Topping.objects.get()) 183 | self.assertEqual(d['pizza'], Pizza.objects.get()) 184 | 185 | def test_save_m2m(self): 186 | restaurant = Restaurant.objects.create(name='Alfredo') 187 | data = { 188 | 'topping-name': 'tomato sauce', 189 | 'pizza-name': 'Plain', 190 | 'pizza-restaurant': [restaurant.id] 191 | } 192 | form = ToppingPizzaRestaurantMultiModelForm(data) 193 | self.assertTrue(form.is_valid()) 194 | d = form.save(commit=False) 195 | d['pizza'].save() 196 | d['topping'].pizza = d['pizza'] 197 | d['topping'].save() 198 | form.save_m2m() 199 | self.assertEqual(d['topping'], Topping.objects.get()) 200 | self.assertEqual(d['pizza'].restaurant.get(), Restaurant.objects.get()) 201 | self.assertEqual(d['pizza'], Pizza.objects.get()) 202 | --------------------------------------------------------------------------------