├── .editorconfig ├── .github ├── SUPPORT.md └── workflows │ └── tests.yml ├── .gitignore ├── .pre-commit-config.yaml ├── AUTHORS.rst ├── CHANGELOG.rst ├── LICENSE ├── MANIFEST.in ├── README.rst ├── docs ├── Makefile ├── conf.py ├── index.rst ├── make.bat └── pages │ ├── changelog.rst │ ├── formset-customization.rst │ ├── formset-views.rst │ ├── getting-started.rst │ ├── installation.rst │ ├── list-views.rst │ └── quick-examples.rst ├── extra_views ├── __init__.py ├── advanced.py ├── contrib │ ├── __init__.py │ └── mixins.py ├── dates.py ├── formsets.py ├── generic.py └── models.py ├── extra_views_tests ├── __init__.py ├── forms.py ├── formsets.py ├── migrations │ ├── 0001_initial.py │ └── __init__.py ├── models.py ├── settings.py ├── templates │ ├── 404.html │ └── extra_views │ │ ├── address_formset.html │ │ ├── event_calendar_month.html │ │ ├── formsets_multiview.html │ │ ├── inline_formset.html │ │ ├── item_formset.html │ │ ├── item_list.html │ │ ├── order_and_items.html │ │ ├── orderaddress_multiview.html │ │ ├── orderitems_multiview.html │ │ ├── paged_formset.html │ │ ├── sortable_item_list.html │ │ └── success.html ├── tests.py ├── urls.py └── views.py ├── manage.py ├── readthedocs.yaml ├── setup.cfg ├── setup.py └── tox.ini /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig: http://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | end_of_line = lf 7 | indent_size = 4 8 | indent_style = space 9 | quote_type = double 10 | insert_final_newline = true 11 | trim_trailing_whitespace = true 12 | max_line_length = 88 13 | 14 | [*.json] 15 | insert_final_newline = false 16 | -------------------------------------------------------------------------------- /.github/SUPPORT.md: -------------------------------------------------------------------------------- 1 | # A note about django-extra-views maintenance 2 | 3 | Dear fellow Pythonista: This project is currently in maintenance mode -- it was abandoned by the original author and taken into custody by me, @jonashaag. 4 | 5 | I can't spend a lot of time on the project, but will do my best to triage any issues and give guidance for those who want to contribute patches to the project. 6 | 7 | If you find any bugs in this library, **please consider submitting a pull request** that fixes your bug, even if it's trivial to fix. 8 | 9 | On a related note: If you've ever wanted to become a core member of an open-source project, this is your chance :-) Contact me at jonas %AT% lophus %DOT% org. 10 | -------------------------------------------------------------------------------- /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | on: [push, pull_request] 3 | env: 4 | LATEST_PYTHON_VERSION: "3.13" 5 | jobs: 6 | tests: 7 | if: github.repository == 'AndrewIngram/django-extra-views' 8 | runs-on: ubuntu-22.04 9 | strategy: 10 | matrix: 11 | python-version: ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] 12 | name: Python ${{ matrix.python-version }} tests 13 | steps: 14 | - uses: actions/checkout@v4 15 | - name: Set up Python ${{ matrix.python-version }} 16 | uses: actions/setup-python@v5 17 | with: 18 | python-version: ${{ matrix.python-version }} 19 | - name: Install dependencies 20 | run: | 21 | python -m pip install --upgrade pip 22 | python -m pip install tox tox-gh-actions 23 | - name: Run tests with tox 24 | run: tox 25 | - name: Upload coverage.xml 26 | if: ${{ matrix.python-version == env.LATEST_PYTHON_VERSION }} 27 | uses: actions/upload-artifact@v4 28 | with: 29 | name: django-extra-views-coverage 30 | path: coverage.xml 31 | if-no-files-found: error 32 | # Disabling until access is available to install Codecov App. 33 | # - name: Upload coverage.xml to Codecov 34 | # if: ${{ matrix.python-version == env.LATEST_PYTHON_VERSION }} 35 | # uses: codecov/codecov-action@v4 36 | # with: 37 | # fail_ci_if_error: true 38 | lint: 39 | if: github.repository == 'AndrewIngram/django-extra-views' 40 | runs-on: ubuntu-latest 41 | strategy: 42 | matrix: 43 | tox-arg: [black, isort, flake8] 44 | steps: 45 | - uses: actions/checkout@v4 46 | - name: Set up Python 47 | uses: actions/setup-python@v5 48 | with: 49 | python-version: ${{ env.LATEST_PYTHON_VERSION }} 50 | - name: Install dependencies 51 | run: | 52 | python -m pip install --upgrade pip 53 | python -m pip install tox 54 | - name: ${{ matrix.tox-arg }} 55 | run: tox -e ${{ matrix.tox-arg }} 56 | 57 | 58 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | .project 3 | .pydevproject 4 | .coverage 5 | .DS_Store 6 | django_extra_views.egg-info/ 7 | htmlcov/ 8 | build/ 9 | docs/_build/ 10 | dist/ 11 | .idea 12 | nosetests.xml 13 | *.sqlite3 14 | .venv/ 15 | venv/ 16 | coverage.xml 17 | /.tox/ 18 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | - repo: https://github.com/psf/black 3 | rev: 23.3.0 4 | hooks: 5 | - id: black 6 | - repo: https://github.com/PyCQA/isort 7 | rev: 5.12.0 8 | hooks: 9 | - id: isort 10 | - repo: https://github.com/PyCQA/flake8 11 | rev: 6.0.0 12 | hooks: 13 | - id: flake8 14 | -------------------------------------------------------------------------------- /AUTHORS.rst: -------------------------------------------------------------------------------- 1 | Primary Author(s): 2 | 3 | * Andrew Ingram (https://github.com/AndrewIngram) 4 | 5 | Other Contributors: 6 | 7 | * Sergey Fursov (https://github.com/GeyseR) 8 | * Pavel Zhukov (https://github.com/zeus) 9 | * Pi Delport (https://github.com/pjdelport) 10 | * jgsogo (https://github.com/jgsogo) 11 | * Krzysiek Szularz (https://github.com/szuliq) 12 | * Miguel Restrepo (https://github.com/miguelrestrepo) 13 | * Henry Ward (https://bitbucket.org/henward0) 14 | * Mark Gensler (https://github.com/sdolemelipone) 15 | -------------------------------------------------------------------------------- /CHANGELOG.rst: -------------------------------------------------------------------------------- 1 | Change History 2 | ============== 3 | 4 | 0.17.0 (TBC) 5 | ------------ 6 | 7 | Changes: 8 | ~~~~~~~~ 9 | 10 | 0.16.0 (2025-04-22) 11 | ------------------- 12 | 13 | Changes: 14 | ~~~~~~~~ 15 | Supported Versions: 16 | 17 | ======== ========== 18 | Python Django 19 | ======== ========== 20 | 3.8-3.9 2.2–4.2 21 | 3.10 3.2-5.2 22 | 3.11 4.1-5.2 23 | 3.12 4.2-5.2 24 | 3.13 5.1-5.2 25 | ======== ========== 26 | 27 | - Added `form_kwargs` and `get_form_kwargs()` to all `BaseFormSetFactory` classes for 28 | ease of use. 29 | - Removed official support for Python 3.6 and 3.7, added Python 3.13. 30 | - Added support for Django 5.2. 31 | 32 | 0.15.0 (2024-09-27) 33 | ------------------------- 34 | 35 | Changes: 36 | ~~~~~~~~ 37 | Supported Versions: 38 | 39 | ======== ========== 40 | Python Django 41 | ======== ========== 42 | 3.6-3.7 2.2–3.2 43 | 3.8-3.9 2.2–4.2 44 | 3.10 3.2-5.1 45 | 3.11 4.1-5.1 46 | 3.12 4.2-5.1 47 | ======== ========== 48 | 49 | - Added support for Django 4.0, 4.1, 4.2, 5.0, 5.1 and Python 3.10, 3.11, 3.12. 50 | - Removed support for Django 2.1 and Python 3.5. 51 | 52 | 0.14.0 (2021-06-08) 53 | ------------------------- 54 | 55 | Changes: 56 | ~~~~~~~~ 57 | Supported Versions: 58 | 59 | ======== ========== 60 | Python Django 61 | ======== ========== 62 | 3.5 2.1–2.2 63 | 3.6-3.7 2.1–3.1 64 | 3.8 2.2–3.1 65 | ======== ========== 66 | 67 | - Removed support for Python 2.7. 68 | - Added support for Python 3.8 and Django 3.1. 69 | - Removed the following classes (use the class in parentheses instead): 70 | 71 | - ``BaseFormSetMixin`` (use ``BaseFormSetFactory``). 72 | - ``BaseInlineFormSetMixin`` (use ``BaseInlineFormSetFactory``). 73 | - ``InlineFormSet`` (use ``InlineFormSetFactory``). 74 | - ``BaseGenericInlineFormSetMixin`` (use ``BaseGenericInlineFormSetFactory``). 75 | - ``GenericInlineFormSet`` (use ``GenericInlineFormSetFactory``). 76 | 77 | 0.13.0 (2019-12-20) 78 | ------------------------- 79 | 80 | Changes: 81 | ~~~~~~~~ 82 | Supported Versions: 83 | 84 | ======== ========== 85 | Python Django 86 | ======== ========== 87 | 2.7 1.11 88 | 3.5 1.11–2.2 89 | 3.6-3.7 1.11–3.0 90 | ======== ========== 91 | 92 | - Added ``SuccessMessageMixin`` and ``FormSetSuccessMessageMixin``. 93 | - ``CreateWithInlinesView`` and ``UpdateWithInlinesView`` now call ``self.form_valid`` 94 | method within ``self.forms_valid``. 95 | - Revert ``view.object`` back to it's original value from the GET request if 96 | validation fails for the inline formsets in ``CreateWithInlinesView`` and 97 | ``UpdateWithInlinesview``. 98 | - Added support for Django 3.0. 99 | 100 | 0.12.0 (2018-10-21) 101 | ------------------- 102 | Supported Versions: 103 | 104 | ======== ========== 105 | Python Django 106 | ======== ========== 107 | 2.7 1.11 108 | 3.4 1.11–2.0 109 | 3.5-3.7 1.11–2.1 110 | ======== ========== 111 | 112 | Changes: 113 | ~~~~~~~~ 114 | - Removed setting of ``BaseInlineFormSetMixin.formset_class`` and 115 | ``GenericInlineFormSetMixin.formset_class`` so that ``formset`` can be set in 116 | ``factory_kwargs`` instead. 117 | - Removed ``ModelFormSetMixin.get_context_data`` and 118 | ``BaseInlineFormSetMixin.get_context_data`` as this code was duplicated from 119 | Django's ``MultipleObjectMixin`` and ``SingleObjectMixin`` respectively. 120 | - Renamed ``BaseFormSetMixin`` to ``BaseFormSetFactory``. 121 | - Renamed ``BaseInlineFormSetMixin`` to ``BaseInlineFormSetFactory``. 122 | - Renamed ``InlineFormSet`` to ``InlineFormSetFactory``. 123 | - Renamed ``BaseGenericInlineFormSetMixin`` to ``BaseGenericInlineFormSetFactory``. 124 | - Renamed ``GenericInlineFormSet`` to ``GenericInlineFormSetFactory``. 125 | 126 | All renamed classes will be removed in a future release. 127 | 128 | 129 | 0.11.0 (2018-04-24) 130 | ------------------- 131 | Supported Versions: 132 | 133 | ======== ========== 134 | Python Django 135 | ======== ========== 136 | 2.7 1.11 137 | 3.4–3.6 1.11–2.0 138 | ======== ========== 139 | 140 | Backwards-incompatible changes 141 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 142 | - Dropped support for Django 1.7–1.10. 143 | - Removed support for factory kwargs ``extra``, ``max_num``, ``can_order``, 144 | ``can_delete``, ``ct_field``, ``formfield_callback``, ``fk_name``, 145 | ``widgets``, ``ct_fk_field`` being set on ``BaseFormSetMixin`` and its 146 | subclasses. Use ``BaseFormSetMixin.factory_kwargs`` instead. 147 | - Removed support for formset_kwarg ``save_as_new`` being set on 148 | ``BaseInlineFormSetMixin`` and its subclasses. Use 149 | ``BaseInlineFormSetMixin.formset_kwargs`` instead. 150 | - Removed support for ``get_extra_form_kwargs``. This can be set in the 151 | dictionary key ``form_kwargs`` in ``BaseFormSetMixin.formset_kwargs`` instead. 152 | 153 | 0.10.0 (2018-02-28) 154 | ------------------- 155 | New features: 156 | 157 | - Added SuccessMessageWithInlinesMixin (#151) 158 | - Allow the formset prefix to be overridden (#154) 159 | 160 | Bug fixes: 161 | 162 | - SearchableMixin: Fix reduce() of empty sequence error (#149) 163 | - Add fields attributes (Issue #144, PR #150) 164 | - Fix Django 1.11 AttributeError: This QueryDict instance is immutable (#156) 165 | 166 | 0.9.0 (2017-03-08) 167 | ------------------ 168 | This version supports Django 1.7, 1.8, 1.9, 1.10 (latest minor versions), and Python 2.7, 3.4, 3.5 (latest minor versions). 169 | 170 | - Added Django 1.10 support 171 | - Dropped Django 1.6 support 172 | 173 | 0.8 (2016-06-14) 174 | ---------------- 175 | 176 | This version supports Django 1.6, 1.7, 1.8, 1.9 (latest minor versions), and Python 2.7, 3.4, 3.5 (latest minor versions). 177 | 178 | - Added ``widgets`` attribute setting; allow to change form widgets in the ``ModelFormSetView``. 179 | - Added Django 1.9 support. 180 | - Fixed ``get_context_data()`` usage of ``*args, **kwargs``. 181 | - Fixed silent overwriting of ``ModelForm`` fields to ``__all__``. 182 | 183 | 184 | Backwards-incompatible changes 185 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 186 | 187 | - Dropped support for Django <= 1.5 and Python 3.3. 188 | - Removed the ``extra_views.multi`` module as it had neither documentation nor 189 | test coverage and was broken for some of the supported Django/Python versions. 190 | - This package no longer implicitly set ``fields = '__all__'``. 191 | If you face ``ImproperlyConfigured`` exceptions, you should have a look at the 192 | `Django 1.6 release notes`_ and set the ``fields`` or ``exclude`` attributes 193 | on your ``ModelForm`` or extra-views views. 194 | 195 | .. _Django 1.6 release notes: https://docs.djangoproject.com/en/stable/releases/1.6/#modelform-without-fields-or-exclude 196 | 197 | 198 | 0.7.1 (2015-06-15) 199 | ------------------ 200 | Beginning of this changelog. 201 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License 2 | 3 | Copyright (c) 2012 Andrew Ingram 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include LICENSE 2 | include README.rst 3 | recursive-include extra_views *.py 4 | recursive-include extra_views/contrib *.py 5 | recursive-include extra_views/tests *.py 6 | recursive-include extra_views/tests/templates *.html 7 | recursive-include extra_views/tests/templates/extra_views *.html -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | |build| |codecov| |docs-status| 2 | 3 | Django Extra Views - The missing class-based generic views for Django 4 | ======================================================================== 5 | 6 | Django-extra-views is a Django package which introduces additional class-based views 7 | in order to simplify common design patterns such as those found in the Django 8 | admin interface. 9 | 10 | Supported Python and Django versions: Python 3.6+, Django 2.2-5.1, 11 | see `tox.ini `_ for an up-to-date list. 12 | 13 | Full documentation is available at `read the docs`_. 14 | 15 | .. _read the docs: https://django-extra-views.readthedocs.io/ 16 | 17 | .. |build| image:: https://github.com/AndrewIngram/django-extra-views/workflows/Tests/badge.svg 18 | :target: https://github.com/AndrewIngram/django-extra-views/ 19 | :alt: Build Status 20 | 21 | .. |codecov| image:: https://codecov.io/github/AndrewIngram/django-extra-views/coverage.svg?branch=master 22 | :target: https://codecov.io/github/AndrewIngram/django-extra-views?branch=master 23 | :alt: Coverage Status 24 | 25 | .. |docs-status| image:: https://readthedocs.org/projects/django-extra-views/badge/?version=latest 26 | :target: https://django-extra-views.readthedocs.io/ 27 | :alt: Documentation Status 28 | 29 | .. installation-start 30 | 31 | Installation 32 | ------------ 33 | 34 | Install the stable release from pypi (using pip): 35 | 36 | .. code-block:: sh 37 | 38 | pip install django-extra-views 39 | 40 | Or install the current master branch from github: 41 | 42 | .. code-block:: sh 43 | 44 | pip install -e git://github.com/AndrewIngram/django-extra-views.git#egg=django-extra-views 45 | 46 | Then add ``'extra_views'`` to your ``INSTALLED_APPS``: 47 | 48 | .. code-block:: python 49 | 50 | INSTALLED_APPS = [ 51 | ... 52 | 'extra_views', 53 | ... 54 | ] 55 | 56 | .. installation-end 57 | 58 | .. features-start 59 | 60 | Features 61 | -------- 62 | 63 | - ``FormSet`` and ``ModelFormSet`` views - The formset equivalents of 64 | ``FormView`` and ``ModelFormView``. 65 | - ``InlineFormSetView`` - Lets you edit a formset related to a model (using 66 | Django's ``inlineformset_factory``). 67 | - ``CreateWithInlinesView`` and ``UpdateWithInlinesView`` - Lets you edit a 68 | model and multiple inline formsets all in one view. 69 | - ``GenericInlineFormSetView``, the equivalent of ``InlineFormSetView`` but for 70 | ``GenericForeignKeys``. 71 | - Support for generic inlines in ``CreateWithInlinesView`` and 72 | ``UpdateWithInlinesView``. 73 | - Support for naming each inline or formset in the template context with 74 | ``NamedFormsetsMixin``. 75 | - ``SortableListMixin`` - Generic mixin for sorting functionality in your views. 76 | - ``SearchableListMixin`` - Generic mixin for search functionality in your views. 77 | - ``SuccessMessageMixin`` and ``FormSetSuccessMessageMixin`` - Generic mixins 78 | to display success messages after form submission. 79 | 80 | .. features-end 81 | 82 | Still to do 83 | ----------- 84 | 85 | Add support for pagination in ModelFormSetView and its derivatives, the goal 86 | being to be able to mimic the change_list view in Django's admin. Currently this 87 | is proving difficult because of how Django's MultipleObjectMixin handles pagination. 88 | 89 | .. quick-examples-start 90 | 91 | Quick Examples 92 | -------------- 93 | 94 | FormSetView 95 | ^^^^^^^^^^^^^^^^^^^^^^^ 96 | 97 | Define a :code:`FormSetView`, a view which creates a single formset from 98 | :code:`django.forms.formset_factory` and adds it to the context. 99 | 100 | .. code-block:: python 101 | 102 | from extra_views import FormSetView 103 | from my_forms import AddressForm 104 | 105 | class AddressFormSet(FormSetView): 106 | form_class = AddressForm 107 | template_name = 'address_formset.html' 108 | 109 | Then within ``address_formset.html``, render the formset like this: 110 | 111 | .. code-block:: html 112 | 113 |
114 | ... 115 | {{ formset }} 116 | ... 117 | 118 |
119 | 120 | ModelFormSetView 121 | ^^^^^^^^^^^^^^^^^^^^ 122 | 123 | Define a :code:`ModelFormSetView`, a view which works as :code:`FormSetView` 124 | but instead renders a model formset using 125 | :code:`django.forms.modelformset_factory`. 126 | 127 | .. code-block:: python 128 | 129 | from extra_views import ModelFormSetView 130 | 131 | 132 | class ItemFormSetView(ModelFormSetView): 133 | model = Item 134 | fields = ['name', 'sku'] 135 | template_name = 'item_formset.html' 136 | 137 | CreateWithInlinesView or UpdateWithInlinesView 138 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 139 | 140 | Define :code:`CreateWithInlinesView` and :code:`UpdateWithInlinesView`, 141 | views which render a form to create/update a model instance and its related 142 | inline formsets. Each of the :code:`InlineFormSetFactory` classes use similar 143 | class definitions as the :code:`ModelFormSetView`. 144 | 145 | .. code-block:: python 146 | 147 | from extra_views import CreateWithInlinesView, UpdateWithInlinesView, InlineFormSetFactory 148 | 149 | 150 | class ItemInline(InlineFormSetFactory): 151 | model = Item 152 | fields = ['sku', 'price', 'name'] 153 | 154 | 155 | class ContactInline(InlineFormSetFactory): 156 | model = Contact 157 | fields = ['name', 'email'] 158 | 159 | 160 | class CreateOrderView(CreateWithInlinesView): 161 | model = Order 162 | inlines = [ItemInline, ContactInline] 163 | fields = ['customer', 'name'] 164 | template_name = 'order_and_items.html' 165 | 166 | 167 | class UpdateOrderView(UpdateWithInlinesView): 168 | model = Order 169 | inlines = [ItemInline, ContactInline] 170 | fields = ['customer', 'name'] 171 | template_name = 'order_and_items.html' 172 | 173 | 174 | Then within ``order_and_items.html``, render the formset like this: 175 | 176 | .. code-block:: html 177 | 178 |
179 | ... 180 | {{ form }} 181 | 182 | {% for formset in inlines %} 183 | {{ formset }} 184 | {% endfor %} 185 | ... 186 | 187 |
188 | 189 | .. quick-examples-end 190 | 191 | 192 | Contributing 193 | ------------ 194 | 195 | Pull requests are welcome. To run all tests locally, setup a virtual environment and run 196 | 197 | 198 | .. code-block:: sh 199 | 200 | tox 201 | 202 | Before committing, use ``pre-commit`` to check all formatting and linting 203 | 204 | .. code-block:: sh 205 | 206 | pip install pre-commit 207 | pre-commmit install 208 | 209 | This will automatically run ``black``, ``isort`` and ``flake8`` before the commit is accepted. -------------------------------------------------------------------------------- /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 | # Internal variables. 11 | PAPEROPT_a4 = -D latex_paper_size=a4 12 | PAPEROPT_letter = -D latex_paper_size=letter 13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 14 | # the i18n builder cannot share the environment and doctrees with the others 15 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 16 | 17 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 18 | 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 " latexpdf to make LaTeX files and run them through pdflatex" 32 | @echo " text to make text files" 33 | @echo " man to make manual pages" 34 | @echo " texinfo to make Texinfo files" 35 | @echo " info to make Texinfo files and run them through makeinfo" 36 | @echo " gettext to make PO message catalogs" 37 | @echo " changes to make an overview of all changed/added/deprecated items" 38 | @echo " linkcheck to check all external links for integrity" 39 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 40 | 41 | clean: 42 | -rm -rf $(BUILDDIR)/* 43 | 44 | html: 45 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 46 | @echo 47 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 48 | 49 | dirhtml: 50 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 51 | @echo 52 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 53 | 54 | singlehtml: 55 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 56 | @echo 57 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 58 | 59 | pickle: 60 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 61 | @echo 62 | @echo "Build finished; now you can process the pickle files." 63 | 64 | json: 65 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 66 | @echo 67 | @echo "Build finished; now you can process the JSON files." 68 | 69 | htmlhelp: 70 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 71 | @echo 72 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 73 | ".hhp project file in $(BUILDDIR)/htmlhelp." 74 | 75 | qthelp: 76 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 77 | @echo 78 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 79 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 80 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/DjangoExtraViews.qhcp" 81 | @echo "To view the help file:" 82 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/DjangoExtraViews.qhc" 83 | 84 | devhelp: 85 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 86 | @echo 87 | @echo "Build finished." 88 | @echo "To view the help file:" 89 | @echo "# mkdir -p $$HOME/.local/share/devhelp/DjangoExtraViews" 90 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/DjangoExtraViews" 91 | @echo "# devhelp" 92 | 93 | epub: 94 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 95 | @echo 96 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 97 | 98 | latex: 99 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 100 | @echo 101 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 102 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 103 | "(use \`make latexpdf' here to do that automatically)." 104 | 105 | latexpdf: 106 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 107 | @echo "Running LaTeX files through pdflatex..." 108 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 109 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 110 | 111 | text: 112 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 113 | @echo 114 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 115 | 116 | man: 117 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 118 | @echo 119 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 120 | 121 | texinfo: 122 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 123 | @echo 124 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 125 | @echo "Run \`make' in that directory to run these through makeinfo" \ 126 | "(use \`make info' here to do that automatically)." 127 | 128 | info: 129 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 130 | @echo "Running Texinfo files through makeinfo..." 131 | make -C $(BUILDDIR)/texinfo info 132 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 133 | 134 | gettext: 135 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 136 | @echo 137 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 138 | 139 | changes: 140 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 141 | @echo 142 | @echo "The overview file is in $(BUILDDIR)/changes." 143 | 144 | linkcheck: 145 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 146 | @echo 147 | @echo "Link check complete; look for any errors in the above output " \ 148 | "or in $(BUILDDIR)/linkcheck/output.txt." 149 | 150 | doctest: 151 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 152 | @echo "Testing of doctests in the sources finished, look at the " \ 153 | "results in $(BUILDDIR)/doctest/output.txt." 154 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Django Extra Views documentation build configuration file, created by 4 | # sphinx-quickstart on Sun Jan 6 03:11:50 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 os 15 | import re 16 | import sys 17 | 18 | # If extensions (or modules to document with autodoc) are in another directory, 19 | # add these directories to sys.path here. If the directory is relative to the 20 | # documentation root, use os.path.abspath to make it absolute, like shown here. 21 | # sys.path.insert(0, os.path.abspath('.')) 22 | 23 | # -- General configuration ----------------------------------------------------- 24 | 25 | # If your documentation needs a minimal Sphinx version, state it here. 26 | # needs_sphinx = '1.0' 27 | 28 | # Add any Sphinx extension module names here, as strings. They can be extensions 29 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 30 | extensions = ["sphinx.ext.autodoc", "sphinx.ext.intersphinx"] 31 | 32 | # Add any paths that contain templates here, relative to this directory. 33 | templates_path = ["_templates"] 34 | 35 | # The suffix of source filenames. 36 | source_suffix = ".rst" 37 | 38 | # The encoding of source files. 39 | # source_encoding = 'utf-8-sig' 40 | 41 | # The master toctree document. 42 | master_doc = "index" 43 | 44 | # General information about the project. 45 | project = "Django Extra Views" 46 | copyright = "2013, Andrew Ingram" 47 | 48 | # The version info for the project you're documenting, acts as replacement for 49 | # |version| and |release|, also used in various other places throughout the 50 | # built documents. 51 | # 52 | with open("../extra_views/__init__.py", "rb") as f: 53 | # The full version, including alpha/beta/rc tags. 54 | release = str(re.search('__version__ = "(.+?)"', f.read().decode("utf-8")).group(1)) 55 | # The short X.Y version. 56 | version = release.rpartition(".")[0] 57 | 58 | # The language for content autogenerated by Sphinx. Refer to documentation 59 | # for a list of supported languages. 60 | # language = None 61 | 62 | # There are two options for replacing |today|: either, you set today to some 63 | # non-false value, then it is used: 64 | # today = '' 65 | # Else, today_fmt is used as the format for a strftime call. 66 | # today_fmt = '%B %d, %Y' 67 | 68 | # List of patterns, relative to source directory, that match files and 69 | # directories to ignore when looking for source files. 70 | exclude_patterns = ["_build"] 71 | 72 | # The reST default role (used for this markup: `text`) to use for all documents. 73 | # default_role = None 74 | 75 | # If true, '()' will be appended to :func: etc. cross-reference text. 76 | # add_function_parentheses = True 77 | 78 | # If true, the current module name will be prepended to all description 79 | # unit titles (such as .. function::). 80 | # add_module_names = True 81 | 82 | # If true, sectionauthor and moduleauthor directives will be shown in the 83 | # output. They are ignored by default. 84 | # show_authors = False 85 | 86 | # The name of the Pygments (syntax highlighting) style to use. 87 | pygments_style = "sphinx" 88 | 89 | # A list of ignored prefixes for module index sorting. 90 | # modindex_common_prefix = [] 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 | on_rtd = os.environ.get("READTHEDOCS", None) == "True" 98 | if on_rtd: 99 | html_theme = "default" 100 | else: 101 | html_theme = "nature" 102 | 103 | # Theme options are theme-specific and customize the look and feel of a theme 104 | # further. For a list of options available for each theme, see the 105 | # documentation. 106 | # html_theme_options = {} 107 | 108 | # Add any paths that contain custom themes here, relative to this directory. 109 | # html_theme_path = [] 110 | 111 | # The name for this set of Sphinx documents. If None, it defaults to 112 | # " v documentation". 113 | # html_title = None 114 | 115 | # A shorter title for the navigation bar. Default is the same as html_title. 116 | # html_short_title = None 117 | 118 | # The name of an image file (relative to this directory) to place at the top 119 | # of the sidebar. 120 | # html_logo = None 121 | 122 | # The name of an image file (within the static path) to use as favicon of the 123 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 124 | # pixels large. 125 | # html_favicon = None 126 | 127 | # Add any paths that contain custom static files (such as style sheets) here, 128 | # relative to this directory. They are copied after the builtin static files, 129 | # so a file named "default.css" will overwrite the builtin "default.css". 130 | html_static_path = ["_static"] 131 | 132 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 133 | # using the given strftime format. 134 | # html_last_updated_fmt = '%b %d, %Y' 135 | 136 | # If true, SmartyPants will be used to convert quotes and dashes to 137 | # typographically correct entities. 138 | # html_use_smartypants = True 139 | 140 | # Custom sidebar templates, maps document names to template names. 141 | # html_sidebars = {} 142 | 143 | # Additional templates that should be rendered to pages, maps page names to 144 | # template names. 145 | # html_additional_pages = {} 146 | 147 | # If false, no module index is generated. 148 | # html_domain_indices = True 149 | 150 | # If false, no index is generated. 151 | # html_use_index = True 152 | 153 | # If true, the index is split into individual pages for each letter. 154 | # html_split_index = False 155 | 156 | # If true, links to the reST sources are added to the pages. 157 | # html_show_sourcelink = True 158 | 159 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 160 | # html_show_sphinx = True 161 | 162 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 163 | # html_show_copyright = True 164 | 165 | # If true, an OpenSearch description file will be output, and all pages will 166 | # contain a tag referring to it. The value of this option must be the 167 | # base URL from which the finished HTML is served. 168 | # html_use_opensearch = '' 169 | 170 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 171 | # html_file_suffix = None 172 | 173 | # Output file base name for HTML help builder. 174 | htmlhelp_basename = "DjangoExtraViewsdoc" 175 | 176 | 177 | # -- Options for LaTeX output -------------------------------------------------- 178 | 179 | latex_elements = { 180 | # The paper size ('letterpaper' or 'a4paper'). 181 | #'papersize': 'letterpaper', 182 | # The font size ('10pt', '11pt' or '12pt'). 183 | #'pointsize': '10pt', 184 | # Additional stuff for the LaTeX preamble. 185 | #'preamble': '', 186 | } 187 | 188 | # Grouping the document tree into LaTeX files. List of tuples 189 | # (source start file, target name, title, author, documentclass [howto/manual]). 190 | latex_documents = [ 191 | ( 192 | "index", 193 | "DjangoExtraViews.tex", 194 | "Django Extra Views Documentation", 195 | "Andrew Ingram", 196 | "manual", 197 | ) 198 | ] 199 | 200 | # The name of an image file (relative to this directory) to place at the top of 201 | # the title page. 202 | # latex_logo = None 203 | 204 | # For "manual" documents, if this is true, then toplevel headings are parts, 205 | # not chapters. 206 | # latex_use_parts = False 207 | 208 | # If true, show page references after internal links. 209 | # latex_show_pagerefs = False 210 | 211 | # If true, show URL addresses after external links. 212 | # latex_show_urls = False 213 | 214 | # Documents to append as an appendix to all manuals. 215 | # latex_appendices = [] 216 | 217 | # If false, no module index is generated. 218 | # latex_domain_indices = True 219 | 220 | 221 | # -- Options for manual page output -------------------------------------------- 222 | 223 | # One entry per manual page. List of tuples 224 | # (source start file, name, description, authors, manual section). 225 | man_pages = [ 226 | ( 227 | "index", 228 | "djangoextraviews", 229 | "Django Extra Views Documentation", 230 | ["Andrew Ingram"], 231 | 1, 232 | ) 233 | ] 234 | 235 | # If true, show URL addresses after external links. 236 | # man_show_urls = False 237 | 238 | 239 | # -- Options for Texinfo output ------------------------------------------------ 240 | 241 | # Grouping the document tree into Texinfo files. List of tuples 242 | # (source start file, target name, title, author, 243 | # dir menu entry, description, category) 244 | texinfo_documents = [ 245 | ( 246 | "index", 247 | "DjangoExtraViews", 248 | "Django Extra Views Documentation", 249 | "Andrew Ingram", 250 | "DjangoExtraViews", 251 | "One line description of project.", 252 | "Miscellaneous", 253 | ) 254 | ] 255 | 256 | # Documents to append as an appendix to all manuals. 257 | # texinfo_appendices = [] 258 | 259 | # If false, no module index is generated. 260 | # texinfo_domain_indices = True 261 | 262 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 263 | # texinfo_show_urls = 'footnote' 264 | 265 | 266 | # Example configuration for intersphinx: refer to the Python standard library. 267 | intersphinx_mapping = {"python": ("http://docs.python.org/", None)} 268 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | ============================================== 2 | django-extra-views 3 | ============================================== 4 | 5 | Django Extra Views provides a number of additional class-based generic views to 6 | complement those provide by Django itself. These mimic some of the functionality 7 | available through the standard admin interface, including Model, Inline and 8 | Generic Formsets. 9 | 10 | .. include:: ../README.rst 11 | :start-after: features-start 12 | :end-before: features-end 13 | 14 | Table of Contents 15 | ----------------- 16 | 17 | .. toctree:: 18 | :maxdepth: 2 19 | 20 | pages/getting-started 21 | pages/formset-views 22 | pages/formset-customization 23 | pages/list-views 24 | 25 | 26 | Reference 27 | --------- 28 | 29 | .. toctree:: 30 | :maxdepth: 1 31 | 32 | pages/changelog 33 | -------------------------------------------------------------------------------- /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. linkcheck to check all external links for integrity 37 | echo. doctest to run all doctests embedded in the documentation if enabled 38 | goto end 39 | ) 40 | 41 | if "%1" == "clean" ( 42 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 43 | del /q /s %BUILDDIR%\* 44 | goto end 45 | ) 46 | 47 | if "%1" == "html" ( 48 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 49 | if errorlevel 1 exit /b 1 50 | echo. 51 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 52 | goto end 53 | ) 54 | 55 | if "%1" == "dirhtml" ( 56 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 57 | if errorlevel 1 exit /b 1 58 | echo. 59 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 60 | goto end 61 | ) 62 | 63 | if "%1" == "singlehtml" ( 64 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 65 | if errorlevel 1 exit /b 1 66 | echo. 67 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 68 | goto end 69 | ) 70 | 71 | if "%1" == "pickle" ( 72 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 73 | if errorlevel 1 exit /b 1 74 | echo. 75 | echo.Build finished; now you can process the pickle files. 76 | goto end 77 | ) 78 | 79 | if "%1" == "json" ( 80 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 81 | if errorlevel 1 exit /b 1 82 | echo. 83 | echo.Build finished; now you can process the JSON files. 84 | goto end 85 | ) 86 | 87 | if "%1" == "htmlhelp" ( 88 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 89 | if errorlevel 1 exit /b 1 90 | echo. 91 | echo.Build finished; now you can run HTML Help Workshop with the ^ 92 | .hhp project file in %BUILDDIR%/htmlhelp. 93 | goto end 94 | ) 95 | 96 | if "%1" == "qthelp" ( 97 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 98 | if errorlevel 1 exit /b 1 99 | echo. 100 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 101 | .qhcp project file in %BUILDDIR%/qthelp, like this: 102 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\DjangoExtraViews.qhcp 103 | echo.To view the help file: 104 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\DjangoExtraViews.ghc 105 | goto end 106 | ) 107 | 108 | if "%1" == "devhelp" ( 109 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 110 | if errorlevel 1 exit /b 1 111 | echo. 112 | echo.Build finished. 113 | goto end 114 | ) 115 | 116 | if "%1" == "epub" ( 117 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 118 | if errorlevel 1 exit /b 1 119 | echo. 120 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 121 | goto end 122 | ) 123 | 124 | if "%1" == "latex" ( 125 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 129 | goto end 130 | ) 131 | 132 | if "%1" == "text" ( 133 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 134 | if errorlevel 1 exit /b 1 135 | echo. 136 | echo.Build finished. The text files are in %BUILDDIR%/text. 137 | goto end 138 | ) 139 | 140 | if "%1" == "man" ( 141 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 142 | if errorlevel 1 exit /b 1 143 | echo. 144 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 145 | goto end 146 | ) 147 | 148 | if "%1" == "texinfo" ( 149 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 150 | if errorlevel 1 exit /b 1 151 | echo. 152 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 153 | goto end 154 | ) 155 | 156 | if "%1" == "gettext" ( 157 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 158 | if errorlevel 1 exit /b 1 159 | echo. 160 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 161 | goto end 162 | ) 163 | 164 | if "%1" == "changes" ( 165 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 166 | if errorlevel 1 exit /b 1 167 | echo. 168 | echo.The overview file is in %BUILDDIR%/changes. 169 | goto end 170 | ) 171 | 172 | if "%1" == "linkcheck" ( 173 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 174 | if errorlevel 1 exit /b 1 175 | echo. 176 | echo.Link check complete; look for any errors in the above output ^ 177 | or in %BUILDDIR%/linkcheck/output.txt. 178 | goto end 179 | ) 180 | 181 | if "%1" == "doctest" ( 182 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 183 | if errorlevel 1 exit /b 1 184 | echo. 185 | echo.Testing of doctests in the sources finished, look at the ^ 186 | results in %BUILDDIR%/doctest/output.txt. 187 | goto end 188 | ) 189 | 190 | :end 191 | -------------------------------------------------------------------------------- /docs/pages/changelog.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../../CHANGELOG.rst 2 | -------------------------------------------------------------------------------- /docs/pages/formset-customization.rst: -------------------------------------------------------------------------------- 1 | Formset Customization Examples 2 | ============================== 3 | 4 | Overriding formset_kwargs and factory_kwargs at run time 5 | ------------------------------------------------------------------------- 6 | If the values in :code:`factory_kwargs`, :code:`formset_kwargs` and :code:`forms_kwargs` 7 | need to be modified at run time, they can be set by overloading the appropriate method 8 | on any formset view (model, inline or generic) or the 9 | :code:`InlineFormSetFactory` classes: 10 | 11 | .. code-block:: python 12 | 13 | from extra_views import FormSetView 14 | 15 | 16 | class AddressFormSetView(FormSetView): 17 | ... 18 | 19 | def get_factory_kwargs(self): 20 | kwargs = super(AddressFormSetView, self).get_factory_kwargs() 21 | # modify kwargs here 22 | return kwargs 23 | 24 | def get_formset_kwargs(self): 25 | kwargs = super(AddressFormSetView, self).get_formset_kwargs() 26 | # modify kwargs here 27 | return kwargs 28 | 29 | def get_form_kwargs(self): 30 | kwargs = super(AddressFormSetView, self).get_form_kwargs() 31 | # modify kwargs here 32 | return kwargs 33 | 34 | 35 | Overriding the the base formset class 36 | ------------------------------------- 37 | 38 | The :code:`formset_class` option should be used if you intend to override the 39 | formset methods of a view or a subclass of :code:`InlineFormSetFactory`. 40 | 41 | For example, imagine you'd like to add your custom :code:`clean` method 42 | for an inline formset view. Then, define a custom formset class, a subclass of 43 | Django's :code:`BaseInlineFormSet`, like this: 44 | 45 | .. code-block:: python 46 | 47 | from django.forms.models import BaseInlineFormSet 48 | 49 | class ItemInlineFormSet(BaseInlineFormSet): 50 | 51 | def clean(self): 52 | # ... 53 | # Your custom clean logic goes here 54 | 55 | 56 | Now, in your :code:`InlineFormSetView` sub-class, use your formset class via 57 | :code:`formset_class` setting, like this: 58 | 59 | .. code-block:: python 60 | 61 | from extra_views import InlineFormSetView 62 | from my_app.models import Item 63 | from my_app.forms import ItemForm 64 | 65 | class ItemInlineView(InlineFormSetView): 66 | model = Item 67 | form_class = ItemForm 68 | formset_class = ItemInlineFormSet # enables our custom inline 69 | 70 | This will enable :code:`clean` method being executed on the formset used by 71 | :code:`ItemInlineView`. 72 | 73 | Initial data for ModelFormSet and InlineFormSet 74 | ----------------------------------------------- 75 | 76 | Passing initial data into ModelFormSet and InlineFormSet works slightly 77 | differently to a regular FormSet. The data passed in from :code:`initial` will 78 | be inserted into the :code:`extra` forms of the formset. Only the data from 79 | :code:`get_queryset()` will be inserted into the initial rows: 80 | 81 | .. code-block:: python 82 | 83 | from extra_views import ModelFormSetView 84 | from my_app.models import Item 85 | 86 | 87 | class ItemFormSetView(ModelFormSetView): 88 | template_name = 'item_formset.html' 89 | model = Item 90 | factory_kwargs = {'extra': 10} 91 | initial = [{'name': 'example1'}, {'name': 'example2'}] 92 | 93 | The above will result in a formset containing a form for each instance of 94 | :code:`Item` in the database, followed by 2 forms containing the extra initial data, 95 | followed by 8 empty forms. 96 | 97 | Altenatively, initial data can be determined at run time and passed in by 98 | overloading :code:`get_initial()`: 99 | 100 | .. code-block:: python 101 | 102 | ... 103 | class ItemFormSetView(ModelFormSetView): 104 | model = Item 105 | template_name = 'item_formset.html' 106 | ... 107 | 108 | def get_initial(self): 109 | # Get a list of initial values for the formset here 110 | initial = [...] 111 | return initial 112 | 113 | Passing arguments to the form constructor 114 | ----------------------------------------- 115 | 116 | In order to change the arguments passed into each form within the 117 | formset, this can be done by either the :code:`form_kwargs` or 118 | :code:`formset_kwargs["form_kwargs"]` attribute of the factory class. 119 | For example, to give every form an initial value of 'example' in the 'name' field: 120 | 121 | .. code-block:: python 122 | 123 | from extra_views import InlineFormSetFactory 124 | 125 | class ItemInline(InlineFormSetFactory): 126 | model = Item 127 | form_kwargs = {'initial': {'name': 'example'}} 128 | 129 | If these need to be modified at run time, it can be done by :code:`get_form_kwargs()`: 130 | 131 | .. code-block:: python 132 | 133 | from extra_views import InlineFormSetFactory 134 | 135 | class ItemInline(InlineFormSetFactory): 136 | model = Item 137 | 138 | def get_form_kwargs(self): 139 | kwargs = super(ItemInline, self).get_form_kwargs() 140 | kwargs['initial'] = get_some_initial_values() 141 | return kwargs 142 | 143 | 144 | Named formsets 145 | -------------- 146 | If you want more control over the names of your formsets (as opposed to 147 | iterating over :code:`inlines`), you can use :code:`NamedFormsetsMixin`: 148 | 149 | .. code-block:: python 150 | 151 | from extra_views import NamedFormsetsMixin 152 | 153 | class CreateOrderView(NamedFormsetsMixin, CreateWithInlinesView): 154 | model = Order 155 | inlines = [ItemInline, TagInline] 156 | inlines_names = ['Items', 'Tags'] 157 | fields = '__all__' 158 | 159 | Then use the appropriate names to render them in the html template: 160 | 161 | .. code-block:: html 162 | 163 | ... 164 | {{ Tags }} 165 | ... 166 | {{ Items }} 167 | ... 168 | 169 | Success messages 170 | ---------------- 171 | When using Django's messages framework, mixins are available to send success 172 | messages in a similar way to ``django.contrib.messages.views.SuccessMessageMixin``. 173 | Ensure that :code:`'django.contrib.messages.middleware.MessageMiddleware'` is included 174 | in the ``MIDDLEWARE`` section of `settings.py`. 175 | 176 | :code:`extra_views.SuccessMessageMixin` is for use with views with multiple 177 | inline formsets. It is used in an identical manner to Django's 178 | SuccessMessageMixin_, making :code:`form.cleaned_data` available for string 179 | interpolation using the :code:`%(field_name)s` syntax: 180 | 181 | .. _SuccessMessageMixin: https://docs.djangoproject.com/en/dev/ref/contrib/messages/#django.contrib.messages.views.SuccessMessageMixin 182 | 183 | .. code-block:: python 184 | 185 | from extra_views import CreateWithInlinesView, SuccessMessageMixin 186 | ... 187 | 188 | class CreateOrderView(SuccessMessageMixin, CreateWithInlinesView): 189 | model = Order 190 | inlines = [ItemInline, ContactInline] 191 | success_message = 'Order %(name)s successfully created!' 192 | ... 193 | 194 | # or instead, set at runtime: 195 | def get_success_message(self, cleaned_data, inlines): 196 | return 'Order with id {} successfully created'.format(self.object.pk) 197 | 198 | Note that the success message mixins should be placed ahead of the main view in 199 | order of class inheritance. 200 | 201 | :code:`extra_views.FormSetSuccessMessageMixin` is for use with views which handle a single 202 | formset. In order to parse any data from the formset, you should override the 203 | :code:`get_success_message` method as below: 204 | 205 | .. code-block:: python 206 | 207 | from extra_views import FormSetView, FormSetSuccessMessageMixin 208 | from my_app.forms import AddressForm 209 | 210 | 211 | class AddressFormSetView(FormSetView): 212 | form_class = AddressForm 213 | success_url = 'success/' 214 | ... 215 | success_message = 'Addresses Updated!' 216 | 217 | # or instead, set at runtime 218 | def get_success_message(self, formset) 219 | # Here you can use the formset in the message if required 220 | return '{} addresses were updated.'.format(len(formset.forms)) 221 | -------------------------------------------------------------------------------- /docs/pages/formset-views.rst: -------------------------------------------------------------------------------- 1 | Formset Views 2 | ============= 3 | 4 | For all of these views we've tried to mimic the API of Django's existing class-based 5 | views as closely as possible, so they should feel natural to anyone who's already 6 | familiar with Django's views. 7 | 8 | 9 | FormSetView 10 | ----------- 11 | 12 | This is the formset equivalent of Django's FormView. Use it when you want to 13 | display a single (non-model) formset on a page. 14 | 15 | A simple formset: 16 | 17 | .. code-block:: python 18 | 19 | from extra_views import FormSetView 20 | from my_app.forms import AddressForm 21 | 22 | 23 | class AddressFormSetView(FormSetView): 24 | template_name = 'address_formset.html' 25 | form_class = AddressForm 26 | success_url = 'success/' 27 | 28 | def get_initial(self): 29 | # return whatever you'd normally use as the initial data for your formset. 30 | return data 31 | 32 | def formset_valid(self, formset): 33 | # do whatever you'd like to do with the valid formset 34 | return super(AddressFormSetView, self).formset_valid(formset) 35 | 36 | and in ``address_formset.html``: 37 | 38 | .. code-block:: html 39 | 40 |
41 | ... 42 | {{ formset }} 43 | ... 44 | 45 |
46 | 47 | This view will render the template ``address_formset.html`` with a context variable 48 | :code:`formset` representing the :code:`AddressFormSet`. Once POSTed and successfully 49 | validated, :code:`formset_valid` will be called (which is where your handling logic 50 | goes), then the view will redirect to :code:`success_url`. 51 | 52 | Formset constructor and factory kwargs 53 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 54 | 55 | FormSetView exposes all the parameters you'd normally be able to pass to the 56 | :code:`django.forms.BaseFormSet` constructor and 57 | :code:`django.forms.formset_factory()`. This can be done by setting the 58 | respective attribute on the class, or :code:`factory_kwargs`, :code:`formset_kwargs` and 59 | :code:`form_kwargs` at the class level. 60 | 61 | Below is an exhaustive list of all formset-related attributes which can be set 62 | at the class level for :code:`FormSetView`: 63 | 64 | .. code-block:: python 65 | 66 | ... 67 | from my_app.forms import AddressForm, BaseAddressFormSet 68 | 69 | 70 | class AddressFormSetView(FormSetView): 71 | template_name = 'address_formset.html' 72 | form_class = AddressForm 73 | formset_class = BaseAddressFormSet 74 | initial = [{'type': 'home'}, {'type': 'work'}] 75 | prefix = 'address-form' 76 | success_url = 'success/' 77 | factory_kwargs = {'extra': 2, 'max_num': None, 78 | 'can_order': False, 'can_delete': False} 79 | formset_kwargs = {'auto_id': 'my_id_%s'} 80 | form_kwargs = {'label_suffix': ':'} 81 | 82 | In the above example, BaseAddressFormSet would be a subclass of 83 | :code:`django.forms.BaseFormSet`. 84 | 85 | ModelFormSetView 86 | ---------------- 87 | 88 | ModelFormSetView makes use of :code:`django.forms.modelformset_factory()`, using the 89 | declarative syntax used in :code:`FormSetView` as well as Django's own class-based 90 | views. So as you'd expect, the simplest usage is as follows: 91 | 92 | .. code-block:: python 93 | 94 | from extra_views import ModelFormSetView 95 | from my_app.models import Item 96 | 97 | 98 | class ItemFormSetView(ModelFormSetView): 99 | model = Item 100 | fields = ['name', 'sku', 'price'] 101 | template_name = 'item_formset.html' 102 | 103 | Rather than setting :code:`fields`, :code:`exclude` can be defined 104 | at the class level as a list of fields to be excluded. 105 | 106 | It is not necessary to define :code:`fields` or :code:`exclude` if a 107 | :code:`form_class` is defined at the class level: 108 | 109 | .. code-block:: python 110 | 111 | ... 112 | from django.forms import ModelForm 113 | 114 | 115 | class ItemForm(ModelForm): 116 | # Custom form definition goes here 117 | fields = ['name', 'sku', 'price'] 118 | 119 | 120 | class ItemFormSetView(ModelFormSetView): 121 | model = Item 122 | form_class = ItemForm 123 | template_name = 'item_formset.html' 124 | 125 | Like :code:`FormSetView`, the :code:`formset` variable is made available in the template 126 | context. By default this will populate the formset with all the instances of 127 | :code:`Item` in the database. You can control this by overriding :code:`get_queryset` on 128 | the class, which could filter on a URL kwarg (:code:`self.kwargs`), for example: 129 | 130 | .. code-block:: python 131 | 132 | class ItemFormSetView(ModelFormSetView): 133 | model = Item 134 | template_name = 'item_formset.html' 135 | 136 | def get_queryset(self): 137 | sku = self.kwargs['sku'] 138 | return super(ItemFormSetView, self).get_queryset().filter(sku=sku) 139 | 140 | 141 | InlineFormSetView 142 | ----------------- 143 | 144 | When you want to edit instances of a particular model related to a parent model 145 | (using a ForeignKey), you'll want to use InlineFormSetView. An example use case 146 | would be editing addresses associated with a particular contact. 147 | 148 | .. code-block:: python 149 | 150 | from extra_views import InlineFormSetView 151 | 152 | 153 | class EditContactAddresses(InlineFormSetView): 154 | model = Contact 155 | inline_model = Address 156 | 157 | ... 158 | 159 | Aside from the use of :code:`model` and :code:`inline_model`, 160 | :code:`InlineFormSetView` works more-or-less in the same way as 161 | :code:`ModelFormSetView`, instead calling :code:`django.forms.inlineformset_factory()`. 162 | 163 | CreateWithInlinesView and UpdateWithInlinesView 164 | ----------------------------------------------- 165 | 166 | These are the most powerful views in the library, they are effectively 167 | replacements for Django's own :code:`CreateView` and :code:`UpdateView`. The key 168 | difference is that they let you include any number of inline formsets (as well 169 | as the parent model's form). This provides functionality much like the Django 170 | Admin change forms. The API should be fairly familiar as well. The list of the 171 | inlines will be passed to the template as context variable `inlines`. 172 | 173 | Here is a simple example that demonstrates the use of each view with normal 174 | inline relationships: 175 | 176 | .. code-block:: python 177 | 178 | from extra_views import CreateWithInlinesView, UpdateWithInlinesView, InlineFormSetFactory 179 | 180 | 181 | class ItemInline(InlineFormSetFactory): 182 | model = Item 183 | fields = ['sku', 'price', 'name'] 184 | 185 | 186 | class ContactInline(InlineFormSetFactory): 187 | model = Contact 188 | fields = ['name', 'email'] 189 | 190 | 191 | class CreateOrderView(CreateWithInlinesView): 192 | model = Order 193 | inlines = [ItemInline, ContactInline] 194 | fields = ['customer', 'name'] 195 | template_name = 'order_and_items.html' 196 | 197 | def get_success_url(self): 198 | return self.object.get_absolute_url() 199 | 200 | 201 | class UpdateOrderView(UpdateWithInlinesView): 202 | model = Order 203 | inlines = [ItemInline, ContactInline] 204 | fields = ['customer', 'name'] 205 | template_name = 'order_and_items.html' 206 | 207 | def get_success_url(self): 208 | return self.object.get_absolute_url() 209 | 210 | and in the html template: 211 | 212 | .. code-block:: html 213 | 214 |
215 | ... 216 | {{ form }} 217 | 218 | {% for formset in inlines %} 219 | {{ formset }} 220 | {% endfor %} 221 | ... 222 | 223 |
224 | 225 | InlineFormSetFactory 226 | ^^^^^^^^^^^^^^^^^^^^ 227 | This class represents all the configuration necessary to generate an inline formset 228 | from :code:`django.inlineformset_factory()`. Each class within in 229 | :code:`CreateWithInlines.inlines` and :code:`UpdateWithInlines.inlines` 230 | should be a subclass of :code:`InlineFormSetFactory`. All the 231 | same methods and attributes as :code:`InlineFormSetView` are available, with the 232 | exception of any view-related attributes and methods, such as :code:`success_url` 233 | or :code:`formset_valid()`: 234 | 235 | .. code-block:: python 236 | 237 | from my_app.forms import ItemForm, BaseItemFormSet 238 | from extra_views import InlineFormSetFactory 239 | 240 | 241 | class ItemInline(InlineFormSetFactory): 242 | model = Item 243 | form_class = ItemForm 244 | formset_class = BaseItemFormSet 245 | initial = [{'name': 'example1'}, {'name', 'example2'}] 246 | prefix = 'item-form' 247 | factory_kwargs = {'extra': 2, 'max_num': None, 248 | 'can_order': False, 'can_delete': False} 249 | formset_kwargs = {'auto_id': 'my_id_%s'} 250 | 251 | 252 | **IMPORTANT**: Note that when using :code:`InlineFormSetFactory`, :code:`model` should be the 253 | *inline* model and **not** the parent model. 254 | 255 | GenericInlineFormSetView 256 | ------------------------ 257 | 258 | In the specific case when you would usually use Django's 259 | :code:`django.contrib.contenttypes.forms.generic_inlineformset_factory()`, you 260 | should use :code:`GenericInlineFormSetView`. The kwargs :code:`ct_field` and 261 | :code:`fk_field` should be set in :code:`factory_kwargs` if they need to be 262 | changed from their default values: 263 | 264 | .. code-block:: python 265 | 266 | from extra_views.generic import GenericInlineFormSetView 267 | 268 | 269 | class EditOrderTags(GenericInlineFormSetView): 270 | model = Order 271 | inline_model = Tag 272 | factory_kwargs = {'ct_field': 'content_type', 'fk_field': 'object_id', 273 | 'max_num': 1} 274 | formset_kwargs = {'save_as_new': True} 275 | 276 | ... 277 | 278 | There is a :code:`GenericInlineFormSetFactory` which is analogous to 279 | :code:`InlineFormSetFactory` for use with generic inline formsets. 280 | 281 | :code:`GenericInlineFormSetFactory` can be used in 282 | :code:`CreateWithInlines.inlines` and :code:`UpdateWithInlines.inlines` in the 283 | obvious way. 284 | -------------------------------------------------------------------------------- /docs/pages/getting-started.rst: -------------------------------------------------------------------------------- 1 | Getting Started 2 | =============== 3 | 4 | .. include:: ./installation.rst 5 | 6 | .. include:: ./quick-examples.rst -------------------------------------------------------------------------------- /docs/pages/installation.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../../README.rst 2 | :start-after: installation-start 3 | :end-before: installation-end 4 | -------------------------------------------------------------------------------- /docs/pages/list-views.rst: -------------------------------------------------------------------------------- 1 | List Views 2 | ========== 3 | 4 | Searchable List Views 5 | --------------------- 6 | You can add search functionality to your ListViews by adding SearchableListMixin 7 | and by setting search_fields: 8 | 9 | .. code-block:: python 10 | 11 | from django.views.generic import ListView 12 | from extra_views import SearchableListMixin 13 | 14 | class SearchableItemListView(SearchableListMixin, ListView): 15 | template_name = 'extra_views/item_list.html' 16 | search_fields = ['name', 'sku'] 17 | model = Item 18 | 19 | In this case ``object_list`` will be filtered if the 'q' query string is provided 20 | (like /searchable/?q=query), or you can manually override ``get_search_query`` 21 | method, to define your own search functionality. 22 | 23 | Also you can define some items in ``search_fields`` as tuple (e.g. 24 | ``[('name', 'iexact', ), 'sku']``) to provide custom lookups for searching. 25 | Default lookup is ``icontains``. We strongly recommend to use only string lookups, 26 | when number fields will convert to strings before comparison to prevent converting errors. 27 | This controlled by ``check_lookups`` setting of SearchableMixin. 28 | 29 | Sortable List View 30 | ------------------ 31 | 32 | .. code-block:: python 33 | 34 | from django.views.generic import ListView 35 | from extra_views import SortableListMixin 36 | 37 | class SortableItemListView(SortableListMixin, ListView): 38 | sort_fields_aliases = [('name', 'by_name'), ('id', 'by_id'), ] 39 | model = Item 40 | 41 | You can hide real field names in query string by define sort_fields_aliases 42 | attribute (see example) or show they as is by define sort_fields. 43 | SortableListMixin adds ``sort_helper`` variable of SortHelper class, 44 | then in template you can use helper functions: 45 | ``{{ sort_helper.get_sort_query_by_FOO }}``, 46 | ``{{ sort_helper.get_sort_query_by_FOO_asc }}``, 47 | ``{{ sort_helper.get_sort_query_by_FOO_desc }}`` and 48 | ``{{ sort_helper.is_sorted_by_FOO }}`` 49 | 50 | -------------------------------------------------------------------------------- /docs/pages/quick-examples.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../../README.rst 2 | :start-after: quick-examples-start 3 | :end-before: quick-examples-end -------------------------------------------------------------------------------- /extra_views/__init__.py: -------------------------------------------------------------------------------- 1 | from extra_views.advanced import ( 2 | CreateWithInlinesView, 3 | FormSetSuccessMessageMixin, 4 | InlineFormSetFactory, 5 | NamedFormsetsMixin, 6 | SuccessMessageMixin, 7 | UpdateWithInlinesView, 8 | ) 9 | from extra_views.contrib.mixins import SearchableListMixin, SortableListMixin 10 | from extra_views.dates import CalendarMonthView 11 | from extra_views.formsets import FormSetView, InlineFormSetView, ModelFormSetView 12 | 13 | __version__ = "0.16.0" 14 | 15 | __all__ = [ 16 | "CreateWithInlinesView", 17 | "FormSetSuccessMessageMixin", 18 | "InlineFormSetFactory", 19 | "NamedFormsetsMixin", 20 | "SuccessMessageMixin", 21 | "UpdateWithInlinesView", 22 | "SearchableListMixin", 23 | "SortableListMixin", 24 | "CalendarMonthView", 25 | "FormSetView", 26 | "InlineFormSetView", 27 | "ModelFormSetView", 28 | ] 29 | -------------------------------------------------------------------------------- /extra_views/advanced.py: -------------------------------------------------------------------------------- 1 | from django.contrib import messages 2 | from django.forms.formsets import all_valid 3 | from django.views.generic.base import ContextMixin 4 | from django.views.generic.detail import SingleObjectTemplateResponseMixin 5 | from django.views.generic.edit import FormView, ModelFormMixin 6 | 7 | from extra_views.formsets import BaseInlineFormSetFactory 8 | 9 | 10 | class InlineFormSetFactory(BaseInlineFormSetFactory): 11 | """ 12 | Class used to create an `InlineFormSet` from `inlineformset_factory` as 13 | one of multiple `InlineFormSet`s within a single view. 14 | 15 | Subclasses `BaseInlineFormSetFactory` and passes in the necessary view arguments. 16 | """ 17 | 18 | def __init__(self, parent_model, request, instance, view_kwargs=None, view=None): 19 | self.inline_model = self.model 20 | self.model = parent_model 21 | self.request = request 22 | self.object = instance 23 | self.kwargs = view_kwargs 24 | self.view = view 25 | 26 | def construct_formset(self): 27 | """ 28 | Overrides construct_formset to attach the model class as 29 | an attribute of the returned formset instance. 30 | """ 31 | formset = super().construct_formset() 32 | formset.model = self.inline_model 33 | return formset 34 | 35 | 36 | class ModelFormWithInlinesMixin(ModelFormMixin): 37 | """ 38 | A mixin that provides a way to show and handle a modelform and inline 39 | formsets in a request. 40 | 41 | The inlines should be subclasses of `InlineFormSetFactory`. 42 | """ 43 | 44 | inlines = [] 45 | 46 | def get_inlines(self): 47 | """ 48 | Returns the inline formset classes 49 | """ 50 | return self.inlines[:] 51 | 52 | def forms_valid(self, form, inlines): 53 | """ 54 | If the form and formsets are valid, save the associated models. 55 | """ 56 | response = self.form_valid(form) 57 | for formset in inlines: 58 | formset.save() 59 | return response 60 | 61 | def forms_invalid(self, form, inlines): 62 | """ 63 | If the form or formsets are invalid, re-render the context data with the 64 | data-filled form and formsets and errors. 65 | """ 66 | return self.render_to_response( 67 | self.get_context_data(form=form, inlines=inlines) 68 | ) 69 | 70 | def construct_inlines(self): 71 | """ 72 | Returns the inline formset instances 73 | """ 74 | inline_formsets = [] 75 | for inline_class in self.get_inlines(): 76 | inline_instance = inline_class( 77 | self.model, self.request, self.object, self.kwargs, self 78 | ) 79 | inline_formset = inline_instance.construct_formset() 80 | inline_formsets.append(inline_formset) 81 | return inline_formsets 82 | 83 | 84 | class ProcessFormWithInlinesView(FormView): 85 | """ 86 | A mixin that renders a form and inline formsets on GET and processes it on POST. 87 | """ 88 | 89 | def get(self, request, *args, **kwargs): 90 | """ 91 | Handles GET requests and instantiates a blank version of the form and formsets. 92 | """ 93 | form_class = self.get_form_class() 94 | form = self.get_form(form_class) 95 | inlines = self.construct_inlines() 96 | return self.render_to_response( 97 | self.get_context_data(form=form, inlines=inlines, **kwargs) 98 | ) 99 | 100 | def post(self, request, *args, **kwargs): 101 | """ 102 | Handles POST requests, instantiating a form and formset instances with the 103 | passed POST variables and then checked for validity. 104 | """ 105 | form_class = self.get_form_class() 106 | form = self.get_form(form_class) 107 | 108 | initial_object = self.object 109 | if form.is_valid(): 110 | self.object = form.save(commit=False) 111 | form_validated = True 112 | else: 113 | form_validated = False 114 | 115 | inlines = self.construct_inlines() 116 | 117 | if all_valid(inlines) and form_validated: 118 | return self.forms_valid(form, inlines) 119 | self.object = initial_object 120 | return self.forms_invalid(form, inlines) 121 | 122 | # PUT is a valid HTTP verb for creating (with a known URL) or editing an 123 | # object, note that browsers only support POST for now. 124 | def put(self, *args, **kwargs): 125 | return self.post(*args, **kwargs) 126 | 127 | 128 | class BaseCreateWithInlinesView(ModelFormWithInlinesMixin, ProcessFormWithInlinesView): 129 | """ 130 | Base view for creating an new object instance with related model instances. 131 | 132 | Using this base class requires subclassing to provide a response mixin. 133 | """ 134 | 135 | def get(self, request, *args, **kwargs): 136 | self.object = None 137 | return super().get(request, *args, **kwargs) 138 | 139 | def post(self, request, *args, **kwargs): 140 | self.object = None 141 | return super().post(request, *args, **kwargs) 142 | 143 | 144 | class CreateWithInlinesView( 145 | SingleObjectTemplateResponseMixin, BaseCreateWithInlinesView 146 | ): 147 | """ 148 | View for creating a new object instance with related model instances, 149 | with a response rendered by template. 150 | """ 151 | 152 | template_name_suffix = "_form" 153 | 154 | 155 | class BaseUpdateWithInlinesView(ModelFormWithInlinesMixin, ProcessFormWithInlinesView): 156 | """ 157 | Base view for updating an existing object with related model instances. 158 | 159 | Using this base class requires subclassing to provide a response mixin. 160 | """ 161 | 162 | def get(self, request, *args, **kwargs): 163 | self.object = self.get_object() 164 | return super().get(request, *args, **kwargs) 165 | 166 | def post(self, request, *args, **kwargs): 167 | self.object = self.get_object() 168 | return super().post(request, *args, **kwargs) 169 | 170 | 171 | class UpdateWithInlinesView( 172 | SingleObjectTemplateResponseMixin, BaseUpdateWithInlinesView 173 | ): 174 | """ 175 | View for updating an object with related model instances, 176 | with a response rendered by template. 177 | """ 178 | 179 | template_name_suffix = "_form" 180 | 181 | 182 | class NamedFormsetsMixin(ContextMixin): 183 | """ 184 | A mixin for use with `CreateWithInlinesView` or `UpdateWithInlinesView` that lets 185 | you define the context variable for each inline. 186 | """ 187 | 188 | inlines_names = [] 189 | 190 | def get_inlines_names(self): 191 | """ 192 | Returns a list of names of context variables for each inline in `inlines`. 193 | """ 194 | return self.inlines_names[:] 195 | 196 | def get_context_data(self, **kwargs): 197 | """ 198 | If `inlines_names` has been defined, add each formset to the context under 199 | its corresponding entry in `inlines_names` 200 | """ 201 | context = {} 202 | inlines_names = self.get_inlines_names() 203 | 204 | if inlines_names: 205 | # We have formset or inlines in context, but never both 206 | context.update(zip(inlines_names, kwargs.get("inlines", []))) 207 | if "formset" in kwargs: 208 | context[inlines_names[0]] = kwargs["formset"] 209 | context.update(kwargs) 210 | return super().get_context_data(**context) 211 | 212 | 213 | class SuccessMessageMixin(object): 214 | """ 215 | Adds success message on views with inlines if django.contrib.messages framework 216 | is used. 217 | In order to use just add mixin in to inheritance before main class, e.g.: 218 | class MyCreateWithInlinesView (SuccessMessageMixin, CreateWithInlinesView): 219 | success_message='Something was created!' 220 | """ 221 | 222 | success_message = "" 223 | 224 | def forms_valid(self, form, inlines): 225 | response = super().forms_valid(form, inlines) 226 | success_message = self.get_success_message(form.cleaned_data, inlines) 227 | if success_message: 228 | messages.success(self.request, success_message) 229 | return response 230 | 231 | def get_success_message(self, cleaned_data, inlines): 232 | return self.success_message % cleaned_data 233 | 234 | 235 | class FormSetSuccessMessageMixin(object): 236 | """ 237 | Adds success message on FormSet views if django.contrib.messages framework 238 | is used. In order to use just add mixin in to inheritance before main 239 | class, e.g.: 240 | class MyFormSetView (FormSetSuccessMessageMixin, ModelFormSetView): 241 | success_message='Something was created!' 242 | """ 243 | 244 | success_message = "" 245 | 246 | def formset_valid(self, formset): 247 | response = super().formset_valid(formset) 248 | success_message = self.get_success_message(formset) 249 | if success_message: 250 | messages.success(self.request, success_message) 251 | return response 252 | 253 | def get_success_message(self, formset): 254 | return self.success_message 255 | -------------------------------------------------------------------------------- /extra_views/contrib/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndrewIngram/django-extra-views/d37136d3c0f6e1194170d50ccb03cae96d860d6c/extra_views/contrib/__init__.py -------------------------------------------------------------------------------- /extra_views/contrib/mixins.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import functools 3 | import operator 4 | 5 | from django.contrib import messages 6 | from django.core.exceptions import ImproperlyConfigured 7 | from django.db.models import Q 8 | from django.views.generic.base import ContextMixin 9 | 10 | VALID_STRING_LOOKUPS = ( 11 | "iexact", 12 | "contains", 13 | "icontains", 14 | "startswith", 15 | "istartswith", 16 | "endswith", 17 | "iendswith", 18 | "search", 19 | "regex", 20 | "iregex", 21 | ) 22 | 23 | 24 | class SearchableListMixin(object): 25 | """ 26 | Filter queryset like a django admin search_fields does, but with little 27 | more intelligence: 28 | if self.search_split is set to True (by default) it will split query 29 | to words (by whitespace) 30 | Also tries to convert each word to date with self.search_date_formats and 31 | then search each word in separate field 32 | e.g. with query 'foo bar' you can find object with 33 | obj.field1__icontains='foo' and obj.field2__icontains=='bar' 34 | 35 | To provide custom lookup just set one of the search_fields to tuple, 36 | e.g. search_fields = [('field1', 'iexact'), 'field2', ('field3', 'startswith')] 37 | 38 | This class is designed to be used with django.generic.ListView 39 | 40 | You could specify query by overriding get_search_query method 41 | by default this method will try to get 'q' key from request.GET 42 | (this can be disabled with search_use_q=False) 43 | """ 44 | 45 | search_fields = ["id"] 46 | search_date_fields = None 47 | search_date_formats = ["%d.%m.%y", "%d.%m.%Y"] 48 | search_split = True 49 | search_use_q = True 50 | check_lookups = True 51 | 52 | def get_words(self, query): 53 | if self.search_split: 54 | return query.split() 55 | return [query] 56 | 57 | def get_search_fields_with_filters(self): 58 | fields = [] 59 | for sf in self.search_fields: 60 | if isinstance(sf, str): 61 | fields.append((sf, "icontains")) 62 | else: 63 | if self.check_lookups and sf[1] not in VALID_STRING_LOOKUPS: 64 | raise ValueError("Invalid string lookup - %s" % sf[1]) 65 | fields.append(sf) 66 | return fields 67 | 68 | def try_convert_to_date(self, word): 69 | """ 70 | Tries to convert word to date(datetime) using search_date_formats 71 | Return None if word fits no one format 72 | """ 73 | for frm in self.search_date_formats: 74 | try: 75 | return datetime.datetime.strptime(word, frm).date() 76 | except ValueError: 77 | pass 78 | return None 79 | 80 | def get_search_query(self): 81 | """ 82 | Get query from request.GET 'q' parameter when search_use_q is set to True 83 | Override this method to provide your own query to search 84 | """ 85 | return self.search_use_q and self.request.GET.get("q", "").strip() 86 | 87 | def get_queryset(self): 88 | qs = super(SearchableListMixin, self).get_queryset() 89 | query = self.get_search_query() 90 | if query: 91 | w_qs = [] 92 | search_pairs = self.get_search_fields_with_filters() 93 | for word in self.get_words(query): 94 | filters = [ 95 | Q(**{"%s__%s" % (pair[0], pair[1]): word}) for pair in search_pairs 96 | ] 97 | if self.search_date_fields: 98 | dt = self.try_convert_to_date(word) 99 | if dt: 100 | filters.extend( 101 | [ 102 | Q(**{field_name: dt}) 103 | for field_name in self.search_date_fields 104 | ] 105 | ) 106 | w_qs.append(functools.reduce(operator.or_, filters)) 107 | qs = qs.filter(functools.reduce(operator.and_, w_qs)) 108 | qs = qs.distinct() 109 | return qs 110 | 111 | 112 | class SortHelper(object): 113 | def __init__( 114 | self, request, sort_fields_aliases, sort_param_name, sort_type_param_name 115 | ): 116 | # Create a list from sort_fields_aliases, in case it is a generator, 117 | # since we want to iterate through it multiple times. 118 | sort_fields_aliases = list(sort_fields_aliases) 119 | 120 | self.initial_params = request.GET.copy() 121 | self.sort_fields = dict(sort_fields_aliases) 122 | self.inv_sort_fields = dict((v, k) for k, v in sort_fields_aliases) 123 | self.initial_sort = self.inv_sort_fields.get( 124 | self.initial_params.get(sort_param_name), None 125 | ) 126 | self.initial_sort_type = self.initial_params.get(sort_type_param_name, "asc") 127 | self.sort_param_name = sort_param_name 128 | self.sort_type_param_name = sort_type_param_name 129 | 130 | for field, alias in self.sort_fields.items(): 131 | setattr( 132 | self, 133 | "get_sort_query_by_%s" % alias, 134 | functools.partial(self.get_params_for_field, field), 135 | ) 136 | setattr( 137 | self, 138 | "get_sort_query_by_%s_asc" % alias, 139 | functools.partial(self.get_params_for_field, field, "asc"), 140 | ) 141 | setattr( 142 | self, 143 | "get_sort_query_by_%s_desc" % alias, 144 | functools.partial(self.get_params_for_field, field, "desc"), 145 | ) 146 | setattr( 147 | self, 148 | "is_sorted_by_%s" % alias, 149 | functools.partial(self.is_sorted_by, field), 150 | ) 151 | 152 | def is_sorted_by(self, field_name): 153 | return field_name == self.initial_sort and self.initial_sort_type or False 154 | 155 | def get_params_for_field(self, field_name, sort_type=None): 156 | """ 157 | If sort_type is None - inverse current sort for field, if no sorted - use asc 158 | """ 159 | if not sort_type: 160 | if self.initial_sort == field_name: 161 | sort_type = "desc" if self.initial_sort_type == "asc" else "asc" 162 | else: 163 | sort_type = "asc" 164 | self.initial_params[self.sort_param_name] = self.sort_fields[field_name] 165 | self.initial_params[self.sort_type_param_name] = sort_type 166 | return "?%s" % self.initial_params.urlencode() 167 | 168 | def get_sort(self): 169 | if not self.initial_sort: 170 | return None 171 | sort = "%s" % self.initial_sort 172 | if self.initial_sort_type == "desc": 173 | sort = "-%s" % sort 174 | return sort 175 | 176 | 177 | class SortableListMixin(ContextMixin): 178 | """ 179 | You can provide either sort_fields as a plain list like 180 | ['id', 'some', 'foo__bar', ...] 181 | or, if you want to hide original field names you can provide list of tuples with 182 | alias that will be used: 183 | [('id', 'by_id'), ('some', 'show_this'), ('foo__bar', 'bar')] 184 | 185 | If sort_param_name exists in query but sort_type_param_name is omitted queryset 186 | will be sorted as 'asc' 187 | """ 188 | 189 | sort_fields = [] 190 | sort_fields_aliases = [] 191 | sort_param_name = "o" 192 | sort_type_param_name = "ot" 193 | 194 | def get_sort_fields(self): 195 | if self.sort_fields: 196 | return zip(self.sort_fields, self.sort_fields) 197 | return self.sort_fields_aliases 198 | 199 | def get_sort_helper(self): 200 | return SortHelper( 201 | self.request, 202 | self.get_sort_fields(), 203 | self.sort_param_name, 204 | self.sort_type_param_name, 205 | ) 206 | 207 | def _sort_queryset(self, queryset): 208 | self.sort_helper = self.get_sort_helper() 209 | sort = self.sort_helper.get_sort() 210 | if sort: 211 | queryset = queryset.order_by(sort) 212 | return queryset 213 | 214 | def get_queryset(self): 215 | qs = super(SortableListMixin, self).get_queryset() 216 | if self.sort_fields and self.sort_fields_aliases: 217 | raise ImproperlyConfigured( 218 | "You should provide sort_fields or sort_fields_aliaces but not both" 219 | ) 220 | return self._sort_queryset(qs) 221 | 222 | def get_context_data(self, **kwargs): 223 | context = {} 224 | if hasattr(self, "sort_helper"): 225 | context["sort_helper"] = self.sort_helper 226 | context.update(kwargs) 227 | return super(SortableListMixin, self).get_context_data(**context) 228 | 229 | 230 | class SuccessMessageWithInlinesMixin(object): 231 | """ 232 | Adds a success message on successful form submission. 233 | """ 234 | 235 | success_message = "" 236 | 237 | def forms_valid(self, form, inlines): 238 | response = super(SuccessMessageWithInlinesMixin, self).forms_valid( 239 | form, inlines 240 | ) 241 | success_message = self.get_success_message(form.cleaned_data) 242 | if success_message: 243 | messages.success(self.request, success_message) 244 | return response 245 | 246 | def get_success_message(self, cleaned_data): 247 | return self.success_message % cleaned_data 248 | -------------------------------------------------------------------------------- /extra_views/dates.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import math 3 | from calendar import Calendar 4 | from collections import defaultdict 5 | 6 | from django.core.exceptions import ImproperlyConfigured 7 | from django.db.models import Q 8 | from django.utils.translation import gettext_lazy as _ 9 | from django.views.generic.dates import ( 10 | DateMixin, 11 | MonthMixin, 12 | YearMixin, 13 | _date_from_string, 14 | ) 15 | from django.views.generic.list import BaseListView, MultipleObjectTemplateResponseMixin 16 | 17 | DAYS = ( 18 | _("Monday"), 19 | _("Tuesday"), 20 | _("Wednesday"), 21 | _("Thursday"), 22 | _("Friday"), 23 | _("Saturday"), 24 | _("Sunday"), 25 | ) 26 | 27 | 28 | def daterange(start_date, end_date): 29 | """ 30 | Returns an iterator of dates between two provided ones 31 | """ 32 | for n in range(int((end_date - start_date).days + 1)): 33 | yield start_date + datetime.timedelta(n) 34 | 35 | 36 | class BaseCalendarMonthView(DateMixin, YearMixin, MonthMixin, BaseListView): 37 | """ 38 | A base view for displaying a calendar month 39 | """ 40 | 41 | first_of_week = 0 # 0 = Monday, 6 = Sunday 42 | paginate_by = None # We don't want to use this part of MultipleObjectMixin 43 | date_field = None 44 | end_date_field = None # For supporting events with duration 45 | 46 | def get_paginate_by(self, queryset): 47 | if self.paginate_by is not None: 48 | raise ImproperlyConfigured( 49 | "'%s' cannot be paginated, it is a calendar view" 50 | % self.__class__.__name__ 51 | ) 52 | return None 53 | 54 | def get_allow_future(self): 55 | return True 56 | 57 | def get_end_date_field(self): 58 | """ 59 | Returns the model field to use for end dates 60 | """ 61 | return self.end_date_field 62 | 63 | def get_start_date(self, obj): 64 | """ 65 | Returns the start date for a model instance 66 | """ 67 | obj_date = getattr(obj, self.get_date_field()) 68 | try: 69 | obj_date = obj_date.date() 70 | except AttributeError: 71 | # It's a date rather than datetime, so we use it as is 72 | pass 73 | return obj_date 74 | 75 | def get_end_date(self, obj): 76 | """ 77 | Returns the end date for a model instance 78 | """ 79 | obj_date = getattr(obj, self.get_end_date_field()) 80 | try: 81 | obj_date = obj_date.date() 82 | except AttributeError: 83 | # It's a date rather than datetime, so we use it as is 84 | pass 85 | return obj_date 86 | 87 | def get_first_of_week(self): 88 | """ 89 | Returns an integer representing the first day of the week. 90 | 91 | 0 represents Monday, 6 represents Sunday. 92 | """ 93 | if self.first_of_week is None: 94 | raise ImproperlyConfigured( 95 | "%s.first_of_week is required." % self.__class__.__name__ 96 | ) 97 | if self.first_of_week not in range(7): 98 | raise ImproperlyConfigured( 99 | "%s.first_of_week must be an integer between 0 and 6." 100 | % self.__class__.__name__ 101 | ) 102 | return self.first_of_week 103 | 104 | def get_queryset(self): 105 | """ 106 | Returns a queryset of models for the month requested 107 | """ 108 | qs = super().get_queryset() 109 | 110 | year = self.get_year() 111 | month = self.get_month() 112 | 113 | date_field = self.get_date_field() 114 | end_date_field = self.get_end_date_field() 115 | 116 | date = _date_from_string( 117 | year, self.get_year_format(), month, self.get_month_format() 118 | ) 119 | 120 | since = date 121 | until = self.get_next_month(date) 122 | 123 | # Adjust our start and end dates to allow for next and previous 124 | # month edges 125 | if since.weekday() != self.get_first_of_week(): 126 | diff = math.fabs(since.weekday() - self.get_first_of_week()) 127 | since = since - datetime.timedelta(days=diff) 128 | 129 | if until.weekday() != ((self.get_first_of_week() + 6) % 7): 130 | diff = math.fabs(((self.get_first_of_week() + 6) % 7) - until.weekday()) 131 | until = until + datetime.timedelta(days=diff) 132 | 133 | if end_date_field: 134 | # 5 possible conditions for showing an event: 135 | 136 | # 1) Single day event, starts after 'since' 137 | # 2) Multi-day event, starts after 'since' and ends before 'until' 138 | # 3) Starts before 'since' and ends after 'since' and before 'until' 139 | # 4) Starts after 'since' but before 'until' and ends after 'until' 140 | # 5) Starts before 'since' and ends after 'until' 141 | predicate1 = Q(**{"%s__gte" % date_field: since, end_date_field: None}) 142 | predicate2 = Q( 143 | **{"%s__gte" % date_field: since, "%s__lt" % end_date_field: until} 144 | ) 145 | predicate3 = Q( 146 | **{ 147 | "%s__lt" % date_field: since, 148 | "%s__gte" % end_date_field: since, 149 | "%s__lt" % end_date_field: until, 150 | } 151 | ) 152 | predicate4 = Q( 153 | **{ 154 | "%s__gte" % date_field: since, 155 | "%s__lt" % date_field: until, 156 | "%s__gte" % end_date_field: until, 157 | } 158 | ) 159 | predicate5 = Q( 160 | **{"%s__lt" % date_field: since, "%s__gte" % end_date_field: until} 161 | ) 162 | return qs.filter( 163 | predicate1 | predicate2 | predicate3 | predicate4 | predicate5 164 | ) 165 | return qs.filter(**{"%s__gte" % date_field: since}) 166 | 167 | def get_context_data(self, **kwargs): 168 | """ 169 | Injects variables necessary for rendering the calendar into the context. 170 | 171 | Variables added are: `calendar`, `weekdays`, `month`, `next_month` and 172 | `previous_month`. 173 | """ 174 | data = super().get_context_data(**kwargs) 175 | 176 | year = self.get_year() 177 | month = self.get_month() 178 | 179 | date = _date_from_string( 180 | year, self.get_year_format(), month, self.get_month_format() 181 | ) 182 | 183 | cal = Calendar(self.get_first_of_week()) 184 | 185 | month_calendar = [] 186 | now = datetime.datetime.now(datetime.timezone.utc) 187 | 188 | date_lists = defaultdict(list) 189 | multidate_objs = [] 190 | 191 | for obj in data["object_list"]: 192 | obj_date = self.get_start_date(obj) 193 | end_date_field = self.get_end_date_field() 194 | 195 | if end_date_field: 196 | end_date = self.get_end_date(obj) 197 | if end_date and end_date != obj_date: 198 | multidate_objs.append( 199 | { 200 | "obj": obj, 201 | "range": [x for x in daterange(obj_date, end_date)], 202 | } 203 | ) 204 | continue # We don't put multi-day events in date_lists 205 | date_lists[obj_date].append(obj) 206 | 207 | for week in cal.monthdatescalendar(date.year, date.month): 208 | week_range = set(daterange(week[0], week[6])) 209 | week_events = [] 210 | 211 | for val in multidate_objs: 212 | intersect_length = len(week_range.intersection(val["range"])) 213 | 214 | if intersect_length: 215 | # Event happens during this week 216 | slot = 1 217 | width = ( 218 | intersect_length # How many days is the event during this week? 219 | ) 220 | nowrap_previous = ( 221 | True # Does the event continue from the previous week? 222 | ) 223 | nowrap_next = True # Does the event continue to the next week? 224 | 225 | if val["range"][0] >= week[0]: 226 | slot = 1 + (val["range"][0] - week[0]).days 227 | else: 228 | nowrap_previous = False 229 | if val["range"][-1] > week[6]: 230 | nowrap_next = False 231 | 232 | week_events.append( 233 | { 234 | "event": val["obj"], 235 | "slot": slot, 236 | "width": width, 237 | "nowrap_previous": nowrap_previous, 238 | "nowrap_next": nowrap_next, 239 | } 240 | ) 241 | 242 | week_calendar = {"events": week_events, "date_list": []} 243 | for day in week: 244 | week_calendar["date_list"].append( 245 | { 246 | "day": day, 247 | "events": date_lists[day], 248 | "today": day == now.date(), 249 | "is_current_month": day.month == date.month, 250 | } 251 | ) 252 | month_calendar.append(week_calendar) 253 | 254 | data["calendar"] = month_calendar 255 | data["weekdays"] = [DAYS[x] for x in cal.iterweekdays()] 256 | data["month"] = date 257 | data["next_month"] = self.get_next_month(date) 258 | data["previous_month"] = self.get_previous_month(date) 259 | 260 | return data 261 | 262 | 263 | class CalendarMonthView(MultipleObjectTemplateResponseMixin, BaseCalendarMonthView): 264 | """ 265 | A view for displaying a calendar month, and rendering a template response 266 | """ 267 | 268 | template_name_suffix = "_calendar_month" 269 | -------------------------------------------------------------------------------- /extra_views/formsets.py: -------------------------------------------------------------------------------- 1 | from django.forms.formsets import formset_factory 2 | from django.forms.models import inlineformset_factory, modelformset_factory 3 | from django.http import HttpResponseRedirect 4 | from django.views.generic.base import ContextMixin, TemplateResponseMixin, View 5 | from django.views.generic.detail import ( 6 | SingleObjectMixin, 7 | SingleObjectTemplateResponseMixin, 8 | ) 9 | from django.views.generic.list import ( 10 | MultipleObjectMixin, 11 | MultipleObjectTemplateResponseMixin, 12 | ) 13 | 14 | 15 | class BaseFormSetFactory(object): 16 | """ 17 | Base class for constructing a FormSet from `formset_factory` in a view. 18 | 19 | Calling `construct_formset` calls all other methods. 20 | """ 21 | 22 | initial = [] 23 | form_class = None 24 | formset_class = None 25 | prefix = None 26 | formset_kwargs = {} 27 | factory_kwargs = {} 28 | form_kwargs = {} 29 | 30 | def construct_formset(self): 31 | """ 32 | Returns an instance of the formset 33 | """ 34 | formset_class = self.get_formset() 35 | return formset_class(**self.get_formset_kwargs()) 36 | 37 | def get_initial(self): 38 | """ 39 | Returns a copy of the initial data to use for formsets on this view. 40 | """ 41 | return self.initial[:] 42 | 43 | def get_prefix(self): 44 | """ 45 | Returns the prefix used for formsets on this view. 46 | """ 47 | return self.prefix 48 | 49 | def get_formset_class(self): 50 | """ 51 | Returns the formset class to use in the formset factory 52 | """ 53 | return self.formset_class 54 | 55 | def get_form_class(self): 56 | """ 57 | Returns the form class to use with the formset in this view 58 | """ 59 | return self.form_class 60 | 61 | def get_form_kwargs(self): 62 | """ 63 | Returns the kwargs to be passed to each form via formset_kwargs["form_kwargs"]. 64 | """ 65 | return self.form_kwargs.copy() 66 | 67 | def get_formset(self): 68 | """ 69 | Returns the formset class from the formset factory 70 | """ 71 | return formset_factory(self.get_form_class(), **self.get_factory_kwargs()) 72 | 73 | def get_formset_kwargs(self): 74 | """ 75 | Returns the keyword arguments for instantiating the formset. 76 | """ 77 | kwargs = self.formset_kwargs.copy() 78 | kwargs.update({"initial": self.get_initial(), "prefix": self.get_prefix()}) 79 | kwargs.setdefault("form_kwargs", {}).update(self.get_form_kwargs()) 80 | 81 | if self.request.method in ("POST", "PUT"): 82 | kwargs.update( 83 | {"data": self.request.POST.copy(), "files": self.request.FILES} 84 | ) 85 | return kwargs 86 | 87 | def get_factory_kwargs(self): 88 | """ 89 | Returns the keyword arguments for calling the formset factory 90 | """ 91 | kwargs = self.factory_kwargs.copy() 92 | if self.get_formset_class(): 93 | kwargs["formset"] = self.get_formset_class() 94 | return kwargs 95 | 96 | 97 | class FormSetMixin(BaseFormSetFactory, ContextMixin): 98 | """ 99 | A view mixin that provides a way to show and handle a single formset in a request. 100 | """ 101 | 102 | success_url = None 103 | 104 | def get_success_url(self): 105 | """ 106 | Returns the supplied URL. 107 | """ 108 | if self.success_url: 109 | url = self.success_url 110 | else: 111 | # Default to returning to the same page 112 | url = self.request.get_full_path() 113 | return url 114 | 115 | def formset_valid(self, formset): 116 | """ 117 | If the formset is valid redirect to the supplied URL 118 | """ 119 | return HttpResponseRedirect(self.get_success_url()) 120 | 121 | def formset_invalid(self, formset): 122 | """ 123 | If the formset is invalid, re-render the context data with the 124 | data-filled formset and errors. 125 | """ 126 | return self.render_to_response(self.get_context_data(formset=formset)) 127 | 128 | 129 | class ModelFormSetMixin(FormSetMixin, MultipleObjectMixin): 130 | """ 131 | A view mixin that provides a way to show and handle a single model formset 132 | in a request. 133 | 134 | Uses `modelformset_factory`. 135 | """ 136 | 137 | exclude = None 138 | fields = None 139 | 140 | def get_formset_kwargs(self): 141 | """ 142 | Returns the keyword arguments for instantiating the formset. 143 | """ 144 | kwargs = super().get_formset_kwargs() 145 | kwargs["queryset"] = self.get_queryset() 146 | return kwargs 147 | 148 | def get_factory_kwargs(self): 149 | """ 150 | Returns the keyword arguments for calling the formset factory 151 | """ 152 | kwargs = super().get_factory_kwargs() 153 | kwargs.setdefault("fields", self.fields) 154 | kwargs.setdefault("exclude", self.exclude) 155 | 156 | if self.get_form_class(): 157 | kwargs["form"] = self.get_form_class() 158 | return kwargs 159 | 160 | def get_formset(self): 161 | """ 162 | Returns the formset class from the model formset factory 163 | """ 164 | return modelformset_factory(self.model, **self.get_factory_kwargs()) 165 | 166 | def formset_valid(self, formset): 167 | """ 168 | If the formset is valid, save the associated models. 169 | """ 170 | self.object_list = formset.save() 171 | return super().formset_valid(formset) 172 | 173 | 174 | class BaseInlineFormSetFactory(BaseFormSetFactory): 175 | """ 176 | Base class for constructing a FormSet from `inlineformset_factory` in a view. 177 | 178 | Calling `construct_formset` calls all other methods. 179 | """ 180 | 181 | model = None 182 | inline_model = None 183 | exclude = None 184 | fields = None 185 | 186 | def get_inline_model(self): 187 | """ 188 | Returns the inline model to use with the inline formset 189 | """ 190 | return self.inline_model 191 | 192 | def get_formset_kwargs(self): 193 | """ 194 | Returns the keyword arguments for instantiating the formset. 195 | """ 196 | kwargs = super().get_formset_kwargs() 197 | kwargs["instance"] = self.object 198 | return kwargs 199 | 200 | def get_factory_kwargs(self): 201 | """ 202 | Returns the keyword arguments for calling the formset factory 203 | """ 204 | kwargs = super().get_factory_kwargs() 205 | kwargs.setdefault("fields", self.fields) 206 | kwargs.setdefault("exclude", self.exclude) 207 | 208 | if self.get_form_class(): 209 | kwargs["form"] = self.get_form_class() 210 | return kwargs 211 | 212 | def get_formset(self): 213 | """ 214 | Returns the formset class from the inline formset factory 215 | """ 216 | return inlineformset_factory( 217 | self.model, self.get_inline_model(), **self.get_factory_kwargs() 218 | ) 219 | 220 | 221 | class InlineFormSetMixin(BaseInlineFormSetFactory, SingleObjectMixin, FormSetMixin): 222 | """ 223 | A view mixin that provides a way to show and handle a single inline formset 224 | in a request. 225 | """ 226 | 227 | def formset_valid(self, formset): 228 | self.object_list = formset.save() 229 | return super().formset_valid(formset) 230 | 231 | 232 | class ProcessFormSetView(View): 233 | """ 234 | A mixin that processes a formset on POST. 235 | """ 236 | 237 | def get(self, request, *args, **kwargs): 238 | """ 239 | Handles GET requests and instantiates a blank version of the formset. 240 | """ 241 | formset = self.construct_formset() 242 | return self.render_to_response(self.get_context_data(formset=formset)) 243 | 244 | def post(self, request, *args, **kwargs): 245 | """ 246 | Handles POST requests, instantiating a formset instance with the passed 247 | POST variables and then checked for validity. 248 | """ 249 | formset = self.construct_formset() 250 | if formset.is_valid(): 251 | return self.formset_valid(formset) 252 | else: 253 | return self.formset_invalid(formset) 254 | 255 | # PUT is a valid HTTP verb for creating (with a known URL) or editing an 256 | # object, note that browsers only support POST for now. 257 | def put(self, *args, **kwargs): 258 | return self.post(*args, **kwargs) 259 | 260 | 261 | class BaseFormSetView(FormSetMixin, ProcessFormSetView): 262 | """ 263 | A base view for displaying a formset 264 | """ 265 | 266 | 267 | class FormSetView(TemplateResponseMixin, BaseFormSetView): 268 | """ 269 | A view for displaying a formset, and rendering a template response 270 | """ 271 | 272 | 273 | class BaseModelFormSetView(ModelFormSetMixin, ProcessFormSetView): 274 | """ 275 | A base view for displaying a model formset 276 | """ 277 | 278 | def get(self, request, *args, **kwargs): 279 | self.object_list = self.get_queryset() 280 | return super().get(request, *args, **kwargs) 281 | 282 | def post(self, request, *args, **kwargs): 283 | self.object_list = self.get_queryset() 284 | return super().post(request, *args, **kwargs) 285 | 286 | 287 | class ModelFormSetView(MultipleObjectTemplateResponseMixin, BaseModelFormSetView): 288 | """ 289 | A view for displaying a model formset, and rendering a template response 290 | """ 291 | 292 | 293 | class BaseInlineFormSetView(InlineFormSetMixin, ProcessFormSetView): 294 | """ 295 | A base view for displaying an inline formset for a queryset belonging to 296 | a parent model 297 | """ 298 | 299 | def get(self, request, *args, **kwargs): 300 | self.object = self.get_object() 301 | return super().get(request, *args, **kwargs) 302 | 303 | def post(self, request, *args, **kwargs): 304 | self.object = self.get_object() 305 | return super().post(request, *args, **kwargs) 306 | 307 | 308 | class InlineFormSetView(SingleObjectTemplateResponseMixin, BaseInlineFormSetView): 309 | """ 310 | A view for displaying an inline formset for a queryset belonging to a parent model 311 | """ 312 | -------------------------------------------------------------------------------- /extra_views/generic.py: -------------------------------------------------------------------------------- 1 | from django.contrib.contenttypes.forms import generic_inlineformset_factory 2 | 3 | from extra_views.formsets import ( 4 | BaseInlineFormSetFactory, 5 | BaseInlineFormSetView, 6 | InlineFormSetMixin, 7 | InlineFormSetView, 8 | ) 9 | 10 | 11 | class BaseGenericInlineFormSetFactory(BaseInlineFormSetFactory): 12 | """ 13 | Base class for constructing a GenericInlineFormSet from 14 | `generic_inlineformset_factory` in a view. 15 | """ 16 | 17 | def get_formset(self): 18 | """ 19 | Returns the final formset class from generic_inlineformset_factory. 20 | """ 21 | result = generic_inlineformset_factory( 22 | self.inline_model, **self.get_factory_kwargs() 23 | ) 24 | return result 25 | 26 | 27 | class GenericInlineFormSetFactory(BaseGenericInlineFormSetFactory): 28 | """ 29 | Class used to create a `GenericInlineFormSet` from `generic_inlineformset_factory` 30 | as one of multiple `GenericInlineFormSet`s within a single view. 31 | 32 | Subclasses `BaseGenericInlineFormSetFactory` and passes in the necessary view 33 | arguments. 34 | """ 35 | 36 | def __init__(self, parent_model, request, instance, view_kwargs=None, view=None): 37 | self.inline_model = self.model 38 | self.model = parent_model 39 | self.request = request 40 | self.object = instance 41 | self.kwargs = view_kwargs 42 | self.view = view 43 | 44 | 45 | class GenericInlineFormSetMixin(BaseGenericInlineFormSetFactory, InlineFormSetMixin): 46 | """ 47 | A mixin that provides a way to show and handle a generic inline formset in a 48 | request. 49 | """ 50 | 51 | 52 | class BaseGenericInlineFormSetView(GenericInlineFormSetMixin, BaseInlineFormSetView): 53 | """ 54 | A base view for displaying a generic inline formset 55 | """ 56 | 57 | 58 | class GenericInlineFormSetView(BaseGenericInlineFormSetView, InlineFormSetView): 59 | """ 60 | A view for displaying a generic inline formset for a queryset belonging to a 61 | parent model 62 | """ 63 | -------------------------------------------------------------------------------- /extra_views/models.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndrewIngram/django-extra-views/d37136d3c0f6e1194170d50ccb03cae96d860d6c/extra_views/models.py -------------------------------------------------------------------------------- /extra_views_tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndrewIngram/django-extra-views/d37136d3c0f6e1194170d50ccb03cae96d860d6c/extra_views_tests/__init__.py -------------------------------------------------------------------------------- /extra_views_tests/forms.py: -------------------------------------------------------------------------------- 1 | from django import forms 2 | 3 | from .models import Item, Order 4 | 5 | 6 | class OrderForm(forms.ModelForm): 7 | class Meta: 8 | model = Order 9 | fields = ["name"] 10 | 11 | def save(self, commit=True): 12 | instance = super().save(commit=commit) 13 | 14 | if commit: 15 | instance.action_on_save = True 16 | instance.save() 17 | 18 | return instance 19 | 20 | 21 | class ItemForm(forms.ModelForm): 22 | flag = forms.BooleanField(initial=True) 23 | 24 | class Meta: 25 | model = Item 26 | fields = ["name", "sku", "price", "order", "status"] 27 | 28 | 29 | class AddressForm(forms.Form): 30 | name = forms.CharField(max_length=255, required=True) 31 | line1 = forms.CharField(max_length=255, required=False) 32 | line2 = forms.CharField(max_length=255, required=False) 33 | city = forms.CharField(max_length=255, required=False) 34 | postcode = forms.CharField(max_length=10, required=True) 35 | 36 | def __init__(self, *args, **kwargs): 37 | super().__init__(*args, **kwargs) 38 | -------------------------------------------------------------------------------- /extra_views_tests/formsets.py: -------------------------------------------------------------------------------- 1 | from django import forms 2 | from django.forms.formsets import BaseFormSet 3 | from django.forms.models import BaseModelFormSet 4 | 5 | COUNTRY_CHOICES = ( 6 | ("gb", "Great Britain"), 7 | ("us", "United States"), 8 | ("ca", "Canada"), 9 | ("au", "Australia"), 10 | ("nz", "New Zealand"), 11 | ) 12 | 13 | 14 | class AddressFormSet(BaseFormSet): 15 | def add_fields(self, form, index): 16 | super().add_fields(form, index) 17 | form.fields["county"] = forms.ChoiceField(choices=COUNTRY_CHOICES, initial="gb") 18 | 19 | 20 | class BaseArticleFormSet(BaseModelFormSet): 21 | def add_fields(self, form, index): 22 | super().add_fields(form, index) 23 | form.fields["notes"] = forms.CharField(initial="Write notes here") 24 | -------------------------------------------------------------------------------- /extra_views_tests/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.1.13 on 2019-10-08 04:42 2 | 3 | import django.db.models.deletion 4 | import django.utils.timezone 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | initial = True 10 | 11 | dependencies = [("contenttypes", "0002_remove_content_type_name")] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name="Contact", 16 | fields=[ 17 | ( 18 | "id", 19 | models.AutoField( 20 | auto_created=True, 21 | primary_key=True, 22 | serialize=False, 23 | verbose_name="ID", 24 | ), 25 | ), 26 | ("name", models.CharField(max_length=255)), 27 | ("email", models.CharField(max_length=255)), 28 | ], 29 | ), 30 | migrations.CreateModel( 31 | name="Event", 32 | fields=[ 33 | ( 34 | "id", 35 | models.AutoField( 36 | auto_created=True, 37 | primary_key=True, 38 | serialize=False, 39 | verbose_name="ID", 40 | ), 41 | ), 42 | ("name", models.CharField(max_length=255)), 43 | ("date", models.DateField()), 44 | ], 45 | ), 46 | migrations.CreateModel( 47 | name="Item", 48 | fields=[ 49 | ( 50 | "id", 51 | models.AutoField( 52 | auto_created=True, 53 | primary_key=True, 54 | serialize=False, 55 | verbose_name="ID", 56 | ), 57 | ), 58 | ("name", models.CharField(max_length=255)), 59 | ("sku", models.CharField(max_length=13)), 60 | ( 61 | "price", 62 | models.DecimalField(db_index=True, decimal_places=2, max_digits=12), 63 | ), 64 | ( 65 | "status", 66 | models.SmallIntegerField( 67 | choices=[ 68 | (0, "Placed"), 69 | (1, "Charged"), 70 | (2, "Shipped"), 71 | (3, "Cancelled"), 72 | ], 73 | db_index=True, 74 | default=0, 75 | ), 76 | ), 77 | ( 78 | "date_placed", 79 | models.DateField( 80 | blank=True, default=django.utils.timezone.now, null=True 81 | ), 82 | ), 83 | ], 84 | ), 85 | migrations.CreateModel( 86 | name="Order", 87 | fields=[ 88 | ( 89 | "id", 90 | models.AutoField( 91 | auto_created=True, 92 | primary_key=True, 93 | serialize=False, 94 | verbose_name="ID", 95 | ), 96 | ), 97 | ("name", models.CharField(max_length=255)), 98 | ("customer", models.CharField(blank=True, default="", max_length=255)), 99 | ("date_created", models.DateTimeField(auto_now_add=True)), 100 | ("date_modified", models.DateTimeField(auto_now=True)), 101 | ("action_on_save", models.BooleanField(default=False)), 102 | ], 103 | ), 104 | migrations.CreateModel( 105 | name="Tag", 106 | fields=[ 107 | ( 108 | "id", 109 | models.AutoField( 110 | auto_created=True, 111 | primary_key=True, 112 | serialize=False, 113 | verbose_name="ID", 114 | ), 115 | ), 116 | ("name", models.CharField(max_length=255)), 117 | ("object_id", models.PositiveIntegerField(null=True)), 118 | ( 119 | "content_type", 120 | models.ForeignKey( 121 | null=True, 122 | on_delete=django.db.models.deletion.CASCADE, 123 | to="contenttypes.ContentType", 124 | ), 125 | ), 126 | ], 127 | ), 128 | migrations.AddField( 129 | model_name="item", 130 | name="order", 131 | field=models.ForeignKey( 132 | on_delete=django.db.models.deletion.CASCADE, 133 | related_name="items", 134 | to="extra_views_tests.Order", 135 | ), 136 | ), 137 | migrations.AddField( 138 | model_name="contact", 139 | name="order", 140 | field=models.ForeignKey( 141 | on_delete=django.db.models.deletion.CASCADE, 142 | related_name="contacts", 143 | to="extra_views_tests.Order", 144 | ), 145 | ), 146 | ] 147 | -------------------------------------------------------------------------------- /extra_views_tests/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndrewIngram/django-extra-views/d37136d3c0f6e1194170d50ccb03cae96d860d6c/extra_views_tests/migrations/__init__.py -------------------------------------------------------------------------------- /extra_views_tests/models.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | 3 | from django.contrib.contenttypes.fields import GenericForeignKey 4 | from django.contrib.contenttypes.models import ContentType 5 | from django.db import models 6 | 7 | try: 8 | from django.utils.timezone import now 9 | except ImportError: 10 | now = datetime.datetime.now 11 | 12 | 13 | STATUS_CHOICES = ((0, "Placed"), (1, "Charged"), (2, "Shipped"), (3, "Cancelled")) 14 | 15 | 16 | class Order(models.Model): 17 | name = models.CharField(max_length=255) 18 | customer = models.CharField(max_length=255, default="", blank=True) 19 | date_created = models.DateTimeField(auto_now_add=True) 20 | date_modified = models.DateTimeField(auto_now=True) 21 | action_on_save = models.BooleanField(default=False) 22 | 23 | def get_absolute_url(self): 24 | return "/inlines/%i/" % self.pk 25 | 26 | def __str__(self): 27 | return self.name 28 | 29 | 30 | class Item(models.Model): 31 | name = models.CharField(max_length=255) 32 | sku = models.CharField(max_length=13) 33 | price = models.DecimalField(decimal_places=2, max_digits=12, db_index=True) 34 | order = models.ForeignKey(Order, related_name="items", on_delete=models.CASCADE) 35 | status = models.SmallIntegerField(default=0, choices=STATUS_CHOICES, db_index=True) 36 | date_placed = models.DateField(default=now, null=True, blank=True) 37 | 38 | def __str__(self): 39 | return "%s (%s)" % (self.name, self.sku) 40 | 41 | 42 | class Contact(models.Model): 43 | name = models.CharField(max_length=255) 44 | email = models.CharField(max_length=255) 45 | order = models.ForeignKey(Order, related_name="contacts", on_delete=models.CASCADE) 46 | 47 | def __str__(self): 48 | return self.name 49 | 50 | 51 | class Tag(models.Model): 52 | name = models.CharField(max_length=255) 53 | content_type = models.ForeignKey(ContentType, null=True, on_delete=models.CASCADE) 54 | object_id = models.PositiveIntegerField(null=True) 55 | content_object = GenericForeignKey("content_type", "object_id") 56 | 57 | def __str__(self): 58 | return self.name 59 | 60 | 61 | class Event(models.Model): 62 | name = models.CharField(max_length=255) 63 | date = models.DateField() 64 | 65 | def __str__(self): 66 | return self.name 67 | -------------------------------------------------------------------------------- /extra_views_tests/settings.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) 4 | BASE_DIR = os.path.dirname(PROJECT_DIR) 5 | 6 | DATABASES = { 7 | "default": { 8 | "ENGINE": "django.db.backends.sqlite3", 9 | "NAME": os.path.join(BASE_DIR, "db.sqlite3"), 10 | } 11 | } 12 | 13 | TEMPLATES = [ 14 | {"BACKEND": "django.template.backends.django.DjangoTemplates", "APP_DIRS": True} 15 | ] 16 | 17 | INSTALLED_APPS = [ 18 | "django.contrib.contenttypes", 19 | "django.contrib.auth", 20 | "extra_views", 21 | "extra_views_tests", 22 | ] 23 | 24 | MIDDLEWARE = [ 25 | "django.middleware.security.SecurityMiddleware", 26 | "django.contrib.sessions.middleware.SessionMiddleware", 27 | "django.middleware.common.CommonMiddleware", 28 | "django.middleware.csrf.CsrfViewMiddleware", 29 | "django.contrib.auth.middleware.AuthenticationMiddleware", 30 | "django.contrib.messages.middleware.MessageMiddleware", 31 | "django.middleware.clickjacking.XFrameOptionsMiddleware", 32 | ] 33 | 34 | ROOT_URLCONF = "extra_views_tests.urls" 35 | 36 | SECRET_KEY = "something not very secret" 37 | -------------------------------------------------------------------------------- /extra_views_tests/templates/404.html: -------------------------------------------------------------------------------- 1 | 404 -------------------------------------------------------------------------------- /extra_views_tests/templates/extra_views/address_formset.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Address Formset 5 | 6 | 7 | 8 |

Address Formset

9 |
10 | 11 | {{ formset }} 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | -------------------------------------------------------------------------------- /extra_views_tests/templates/extra_views/event_calendar_month.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Event Calendar 5 | 6 | 7 | 8 |

Event Calendar

9 | 10 | {{ object_list }} 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /extra_views_tests/templates/extra_views/formsets_multiview.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Order and Address MultiView 5 | 6 | 7 | 8 |
9 | 10 | {{ order_form }} 11 | 12 | 13 | 14 |
15 | 16 |
17 | 18 | {{ items_formset }} 19 | 20 | 21 | 22 |
23 | 24 | 25 | -------------------------------------------------------------------------------- /extra_views_tests/templates/extra_views/inline_formset.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Inline Formset 5 | 6 | 7 | 8 |

Inline Formset

9 |
10 | 11 | {{ formset }} 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | -------------------------------------------------------------------------------- /extra_views_tests/templates/extra_views/item_formset.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Item Formset 5 | 6 | 7 | 8 |

Item Formset

9 |
10 | 11 | {{ formset }} 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | -------------------------------------------------------------------------------- /extra_views_tests/templates/extra_views/item_list.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Item List 5 | 6 | 7 | 8 |

Item List

9 | {% for object in object_list %} 10 | {{ object }} 11 | {% endfor %} 12 | 13 | -------------------------------------------------------------------------------- /extra_views_tests/templates/extra_views/order_and_items.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Order and Items 5 | 6 | 7 | 8 |

Order and Items

9 |
10 | 11 | {{ form }} 12 | 13 | {% for formset in inlines %} 14 | 15 | {{ formset }} 16 | 17 | {% endfor %} 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | -------------------------------------------------------------------------------- /extra_views_tests/templates/extra_views/orderaddress_multiview.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Order and Address MultiView 5 | 6 | 7 | 8 |
9 | 10 | {{ order_form }} 11 | 12 | 13 | 14 |
15 | 16 |
17 | 18 | {{ address_form }} 19 | 20 | 21 | 22 |
23 | 24 | 25 | -------------------------------------------------------------------------------- /extra_views_tests/templates/extra_views/orderitems_multiview.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Order and Items MultiView 5 | 6 | 7 | 8 |
9 | 10 | {{ order_form }} 11 | 12 | 13 | 14 |
15 | 16 |
17 | 18 | {{ items_formset }} 19 | 20 | 21 | 22 |
23 | 24 | 25 | -------------------------------------------------------------------------------- /extra_views_tests/templates/extra_views/paged_formset.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Item Formset 5 | 6 | 7 | 8 |

Item Formset

9 |
10 | 11 | {{ formset }} 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | -------------------------------------------------------------------------------- /extra_views_tests/templates/extra_views/sortable_item_list.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Item List 5 | 6 | 7 | 8 |

Item List

9 | 10 | 11 | 17 | 20 | 21 | {% for object in object_list %} 22 | 23 | 24 | 25 | 26 | {% endfor %} 27 |
12 | Name 13 | asc name 14 | desc name 15 | {% if sort_helper.is_sorted_by_name %} ordered by name {{ sort_helper.is_sorted_by_name }} {% endif %} 16 | 18 | SKU 19 |
{{ object.name }}{{ object.sku }}
28 | 29 | 30 | -------------------------------------------------------------------------------- /extra_views_tests/templates/extra_views/success.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Success 5 | 6 | 7 | 8 |

Success

9 | 10 | 11 | -------------------------------------------------------------------------------- /extra_views_tests/tests.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | from decimal import Decimal as D 3 | from unittest import expectedFailure 4 | 5 | import django 6 | from django.contrib.messages import get_messages 7 | from django.core.exceptions import ImproperlyConfigured 8 | from django.forms import ValidationError 9 | from django.test import RequestFactory, TestCase 10 | 11 | from .models import Event, Item, Order, Tag 12 | from .views import AddressFormSetViewFormKwargs 13 | 14 | 15 | class FormSetViewTests(TestCase): 16 | management_data = { 17 | "form-TOTAL_FORMS": "2", 18 | "form-INITIAL_FORMS": "0", 19 | "form-MAX_NUM_FORMS": "", 20 | } 21 | 22 | @classmethod 23 | def setUpClass(cls): 24 | super().setUpClass() 25 | cls.factory = RequestFactory() 26 | 27 | def test_create(self): 28 | res = self.client.get("/formset/simple/") 29 | self.assertEqual(res.status_code, 200) 30 | self.assertTrue("formset" in res.context_data) 31 | self.assertFalse("form" in res.context_data) 32 | self.assertTemplateUsed(res, "extra_views/address_formset.html") 33 | self.assertRegex( 34 | res.context_data["formset"].__class__.__name__, "Address(Form)?FormSet" 35 | ) 36 | 37 | def test_formset_named(self): 38 | res = self.client.get("/formset/simple/named/") 39 | self.assertEqual(res.status_code, 200) 40 | self.assertEqual( 41 | res.context_data["formset"], res.context_data["AddressFormset"] 42 | ) 43 | 44 | def test_missing_management_form(self): 45 | # Django >=3.2 and does not raise an exception, but returns an error. 46 | if django.__version__ >= "3.2.0": 47 | res = self.client.post("/formset/simple/", {}) 48 | self.assertEqual(200, res.status_code) 49 | formset = res.context_data["formset"] 50 | self.assertFalse(formset.is_valid()) 51 | self.assertIn( 52 | "ManagementForm data is missing or has been tampered with", 53 | formset.non_form_errors()[0], 54 | ) 55 | else: 56 | with self.assertRaisesRegex( 57 | ValidationError, 58 | "ManagementForm data is missing or has been tampered with", 59 | ): 60 | self.client.post("/formset/simple/", {}) 61 | 62 | def test_success(self): 63 | res = self.client.post("/formset/simple/", self.management_data, follow=True) 64 | self.assertRedirects(res, "/formset/simple/", status_code=302) 65 | 66 | def test_success_message(self): 67 | res = self.client.post("/formset/simple/", self.management_data, follow=True) 68 | messages = [ 69 | message.__str__() 70 | for message in get_messages(res.context_data["view"].request) 71 | ] 72 | self.assertIn("Formset objects were created successfully!", messages) 73 | 74 | @expectedFailure 75 | def test_put(self): 76 | res = self.client.put("/formset/simple/", self.management_data, follow=True) 77 | self.assertRedirects(res, "/formset/simple/", status_code=302) 78 | 79 | def test_success_url(self): 80 | res = self.client.post( 81 | "/formset/simple_redirect/", self.management_data, follow=True 82 | ) 83 | self.assertRedirects(res, "/formset/simple_redirect/valid/") 84 | 85 | def test_invalid(self): 86 | data = { 87 | "form-0-name": "Joe Bloggs", 88 | "form-0-city": "", 89 | "form-0-line1": "", 90 | "form-0-line2": "", 91 | "form-0-postcode": "", 92 | } 93 | data.update(self.management_data) 94 | 95 | res = self.client.post("/formset/simple/", data, follow=True) 96 | self.assertEqual(res.status_code, 200) 97 | self.assertTrue("postcode" in res.context_data["formset"].errors[0]) 98 | 99 | def test_formset_class(self): 100 | res = self.client.get("/formset/custom/") 101 | self.assertEqual(res.status_code, 200) 102 | 103 | def test_inital(self): 104 | res = self.client.get("/formset/simple/kwargs/") 105 | self.assertEqual(res.status_code, 200) 106 | initial_forms = res.context_data["formset"].initial_forms 107 | self.assertTrue(initial_forms) 108 | self.assertEqual(initial_forms[0].initial, {"name": "address1"}) 109 | 110 | def test_prefix(self): 111 | res = self.client.get("/formset/simple/kwargs/") 112 | self.assertEqual(res.status_code, 200) 113 | self.assertEqual( 114 | res.context_data["formset"].management_form.prefix, "test_prefix" 115 | ) 116 | 117 | def test_factory_kwargs(self): 118 | res = self.client.get("/formset/simple/kwargs/") 119 | self.assertEqual(res.status_code, 200) 120 | self.assertEqual( 121 | res.context_data["formset"].management_form.initial["MAX_NUM_FORMS"], 27 122 | ) 123 | 124 | def test_formset_kwargs(self): 125 | res = self.client.get("/formset/simple/kwargs/") 126 | self.assertEqual(res.status_code, 200) 127 | self.assertEqual( 128 | res.context_data["formset"].management_form.auto_id, "id_test_%s" 129 | ) 130 | initial_forms = res.context_data["formset"].initial_forms 131 | self.assertTrue(initial_forms) 132 | self.assertTrue(initial_forms[0].empty_permitted) 133 | 134 | def test_form_kwargs_are_merged(self): 135 | request = self.factory.get("/formset/simple/kwargs/") 136 | response = AddressFormSetViewFormKwargs.as_view()(request) 137 | first_form = response.context_data["formset"].forms[0] 138 | self.assertTrue(first_form.empty_permitted) 139 | self.assertEqual(first_form.label_suffix, ":") 140 | 141 | 142 | class ModelFormSetViewTests(TestCase): 143 | management_data = { 144 | "form-TOTAL_FORMS": "2", 145 | "form-INITIAL_FORMS": "0", 146 | "form-MAX_NUM_FORMS": "", 147 | } 148 | 149 | def test_create(self): 150 | res = self.client.get("/modelformset/simple/") 151 | self.assertEqual(res.status_code, 200) 152 | self.assertTrue("formset" in res.context_data) 153 | self.assertFalse("form" in res.context_data) 154 | self.assertTemplateUsed(res, "extra_views/item_formset.html") 155 | self.assertRegex( 156 | res.context_data["formset"].__class__.__name__, "Item(Form)?FormSet" 157 | ) 158 | 159 | def test_override(self): 160 | res = self.client.get("/modelformset/custom/") 161 | self.assertEqual(res.status_code, 200) 162 | form = res.context_data["formset"].forms[0] 163 | self.assertEqual(form["flag"].value(), True) 164 | self.assertEqual(form["notes"].value(), "Write notes here") 165 | 166 | def test_post(self): 167 | order = Order(name="Dummy Order") 168 | order.save() 169 | 170 | data = { 171 | "form-0-name": "Bubble Bath", 172 | "form-0-sku": "1234567890123", 173 | "form-0-price": D("9.99"), 174 | "form-0-order": order.id, 175 | "form-0-status": 0, 176 | } 177 | data.update(self.management_data) 178 | data["form-TOTAL_FORMS"] = "1" 179 | res = self.client.post("/modelformset/simple/", data, follow=True) 180 | self.assertEqual(res.status_code, 200) 181 | self.assertEqual(Item.objects.all().count(), 1) 182 | 183 | def test_context(self): 184 | order = Order(name="Dummy Order") 185 | order.save() 186 | 187 | for i in range(10): 188 | item = Item( 189 | name="Item %i" % i, 190 | sku=str(i) * 13, 191 | price=D("9.99"), 192 | order=order, 193 | status=0, 194 | ) 195 | item.save() 196 | 197 | res = self.client.get("/modelformset/simple/") 198 | self.assertTrue("object_list" in res.context_data) 199 | self.assertEqual(len(res.context_data["object_list"]), 10) 200 | 201 | def test_fields_is_used(self): 202 | res = self.client.get("/modelformset/simple/") 203 | self.assertEqual(res.status_code, 200) 204 | fields = res.context_data["formset"].empty_form.fields 205 | self.assertIn("sku", fields) 206 | self.assertNotIn("date_placed", fields) 207 | 208 | def test_exclude_is_used(self): 209 | res = self.client.get("/modelformset/exclude/") 210 | self.assertEqual(res.status_code, 200) 211 | fields = res.context_data["formset"].empty_form.fields 212 | self.assertIn("date_placed", fields) 213 | self.assertNotIn("sku", fields) 214 | 215 | 216 | class InlineFormSetViewTests(TestCase): 217 | management_data = { 218 | "items-TOTAL_FORMS": "2", 219 | "items-INITIAL_FORMS": "0", 220 | "items-MAX_NUM_FORMS": "", 221 | } 222 | 223 | def test_create(self): 224 | order = Order(name="Dummy Order") 225 | order.save() 226 | 227 | for i in range(10): 228 | item = Item( 229 | name="Item %i" % i, 230 | sku=str(i) * 13, 231 | price=D("9.99"), 232 | order=order, 233 | status=0, 234 | ) 235 | item.save() 236 | 237 | res = self.client.get("/inlineformset/{}/".format(order.id)) 238 | 239 | self.assertTrue("object" in res.context_data) 240 | self.assertTrue("order" in res.context_data) 241 | 242 | self.assertEqual(res.status_code, 200) 243 | self.assertTrue("formset" in res.context_data) 244 | self.assertFalse("form" in res.context_data) 245 | 246 | def test_post(self): 247 | order = Order(name="Dummy Order") 248 | order.save() 249 | data = {} 250 | data.update(self.management_data) 251 | 252 | res = self.client.post("/inlineformset/{}/".format(order.id), data, follow=True) 253 | self.assertEqual(res.status_code, 200) 254 | self.assertTrue("formset" in res.context_data) 255 | self.assertFalse("form" in res.context_data) 256 | 257 | def test_save(self): 258 | order = Order(name="Dummy Order") 259 | order.save() 260 | data = { 261 | "items-0-name": "Bubble Bath", 262 | "items-0-sku": "1234567890123", 263 | "items-0-price": D("9.99"), 264 | "items-0-status": 0, 265 | "items-1-DELETE": True, 266 | } 267 | data.update(self.management_data) 268 | 269 | self.assertEqual(0, order.items.count()) 270 | res = self.client.post("/inlineformset/{}/".format(order.id), data, follow=True) 271 | order = Order.objects.get(id=order.id) 272 | 273 | context_instance = res.context_data["formset"][0].instance 274 | 275 | self.assertEqual("Bubble Bath", context_instance.name) 276 | self.assertEqual("", res.context_data["formset"][1].instance.name) 277 | 278 | self.assertEqual(1, order.items.count()) 279 | 280 | 281 | class GenericInlineFormSetViewTests(TestCase): 282 | def test_get(self): 283 | order = Order(name="Dummy Order") 284 | order.save() 285 | 286 | order2 = Order(name="Other Order") 287 | order2.save() 288 | 289 | tag = Tag(name="Test", content_object=order) 290 | tag.save() 291 | 292 | tag = Tag(name="Test2", content_object=order2) 293 | tag.save() 294 | 295 | res = self.client.get("/genericinlineformset/{}/".format(order.id)) 296 | 297 | self.assertEqual(res.status_code, 200) 298 | self.assertTrue("formset" in res.context_data) 299 | self.assertFalse("form" in res.context_data) 300 | self.assertEqual("Test", res.context_data["formset"].forms[0]["name"].value()) 301 | 302 | def test_post(self): 303 | order = Order(name="Dummy Order") 304 | order.save() 305 | 306 | tag = Tag(name="Test", content_object=order) 307 | tag.save() 308 | 309 | data = { 310 | "extra_views_tests-tag-content_type-object_id-TOTAL_FORMS": 3, 311 | "extra_views_tests-tag-content_type-object_id-INITIAL_FORMS": 1, 312 | "extra_views_tests-tag-content_type-object_id-MAX_NUM_FORMS": "", 313 | "extra_views_tests-tag-content_type-object_id-0-name": "Updated", 314 | "extra_views_tests-tag-content_type-object_id-0-id": 1, 315 | "extra_views_tests-tag-content_type-object_id-1-DELETE": True, 316 | "extra_views_tests-tag-content_type-object_id-2-DELETE": True, 317 | } 318 | 319 | res = self.client.post( 320 | "/genericinlineformset/{}/".format(order.id), data, follow=True 321 | ) 322 | self.assertEqual(res.status_code, 200) 323 | self.assertEqual( 324 | "Updated", res.context_data["formset"].forms[0]["name"].value() 325 | ) 326 | self.assertEqual(1, Tag.objects.count()) 327 | 328 | def test_post2(self): 329 | order = Order(name="Dummy Order") 330 | order.save() 331 | 332 | tag = Tag(name="Test", content_object=order) 333 | tag.save() 334 | 335 | data = { 336 | "extra_views_tests-tag-content_type-object_id-TOTAL_FORMS": 3, 337 | "extra_views_tests-tag-content_type-object_id-INITIAL_FORMS": 1, 338 | "extra_views_tests-tag-content_type-object_id-MAX_NUM_FORMS": "", 339 | "extra_views_tests-tag-content_type-object_id-0-name": "Updated", 340 | "extra_views_tests-tag-content_type-object_id-0-id": tag.id, 341 | "extra_views_tests-tag-content_type-object_id-1-name": "Tag 2", 342 | "extra_views_tests-tag-content_type-object_id-2-name": "Tag 3", 343 | } 344 | 345 | res = self.client.post( 346 | "/genericinlineformset/{}/".format(order.id), data, follow=True 347 | ) 348 | self.assertEqual(res.status_code, 200) 349 | self.assertEqual(3, Tag.objects.count()) 350 | 351 | def test_intial_data_is_used(self): 352 | # Specific test for initial data in genericinlineformset 353 | order = Order(name="Dummy Order") 354 | order.save() 355 | res = self.client.get("/genericinlineformset/{}/".format(order.id)) 356 | self.assertEqual(res.status_code, 200) 357 | extra_forms = res.context_data["formset"].extra_forms 358 | self.assertTrue(extra_forms) 359 | self.assertEqual(extra_forms[0].initial, {"name": "test_tag_name"}) 360 | 361 | 362 | class ModelWithInlinesTests(TestCase): 363 | def test_create(self): 364 | res = self.client.get("/inlines/new/") 365 | self.assertEqual(res.status_code, 200) 366 | self.assertEqual(0, Tag.objects.count()) 367 | 368 | data = { 369 | "name": "Dummy Order", 370 | "items-TOTAL_FORMS": "2", 371 | "items-INITIAL_FORMS": "0", 372 | "items-MAX_NUM_FORMS": "", 373 | "items-0-name": "Bubble Bath", 374 | "items-0-sku": "1234567890123", 375 | "items-0-price": D("9.99"), 376 | "items-0-status": 0, 377 | "items-1-DELETE": True, 378 | "extra_views_tests-tag-content_type-object_id-TOTAL_FORMS": 2, 379 | "extra_views_tests-tag-content_type-object_id-INITIAL_FORMS": 0, 380 | "extra_views_tests-tag-content_type-object_id-MAX_NUM_FORMS": "", 381 | "extra_views_tests-tag-content_type-object_id-0-name": "Test", 382 | "extra_views_tests-tag-content_type-object_id-1-DELETE": True, 383 | } 384 | 385 | res = self.client.post("/inlines/new/", data, follow=True) 386 | 387 | self.assertTrue("object" in res.context_data) 388 | self.assertTrue("order" in res.context_data) 389 | 390 | self.assertEqual(res.status_code, 200) 391 | self.assertEqual(1, Tag.objects.count()) 392 | 393 | # Check that form_valid has been called. 394 | self.assertRedirects(res, "/inlines/1/?form_valid_called=1") 395 | 396 | def test_create_success_message(self): 397 | res = self.client.get("/inlines/new/") 398 | self.assertEqual(res.status_code, 200) 399 | self.assertEqual(0, Tag.objects.count()) 400 | 401 | data = { 402 | "name": "Dummy Order", 403 | "items-TOTAL_FORMS": "2", 404 | "items-INITIAL_FORMS": "0", 405 | "items-MAX_NUM_FORMS": "", 406 | "items-0-name": "Bubble Bath", 407 | "items-0-sku": "1234567890123", 408 | "items-0-price": D("9.99"), 409 | "items-0-status": 0, 410 | "items-1-DELETE": True, 411 | "extra_views_tests-tag-content_type-object_id-TOTAL_FORMS": 2, 412 | "extra_views_tests-tag-content_type-object_id-INITIAL_FORMS": 0, 413 | "extra_views_tests-tag-content_type-object_id-MAX_NUM_FORMS": "", 414 | "extra_views_tests-tag-content_type-object_id-0-name": "Test", 415 | "extra_views_tests-tag-content_type-object_id-1-DELETE": True, 416 | } 417 | 418 | res = self.client.post("/inlines/new/", data, follow=True) 419 | 420 | messages = [ 421 | message.__str__() 422 | for message in get_messages(res.context_data["view"].request) 423 | ] 424 | self.assertIn("Order Dummy Order was created successfully!", messages) 425 | 426 | def test_named_create(self): 427 | res = self.client.get("/inlines/new/named/") 428 | self.assertEqual(res.status_code, 200) 429 | self.assertEqual(res.context_data["Items"], res.context_data["inlines"][0]) 430 | self.assertEqual(res.context_data["Tags"], res.context_data["inlines"][1]) 431 | 432 | def test_validation(self): 433 | data = { 434 | "items-TOTAL_FORMS": "2", 435 | "items-INITIAL_FORMS": "0", 436 | "items-MAX_NUM_FORMS": "", 437 | "items-0-name": "Test Item 1", 438 | "items-0-sku": "", 439 | "items-0-price": "", 440 | "items-0-status": 0, 441 | "items-1-name": "", 442 | "items-1-sku": "", 443 | "items-1-price": "", 444 | "items-1-status": "", 445 | "items-1-DELETE": True, 446 | "extra_views_tests-tag-content_type-object_id-TOTAL_FORMS": 2, 447 | "extra_views_tests-tag-content_type-object_id-INITIAL_FORMS": 0, 448 | "extra_views_tests-tag-content_type-object_id-MAX_NUM_FORMS": "", 449 | "extra_views_tests-tag-content_type-object_id-0-name": "Test", 450 | "extra_views_tests-tag-content_type-object_id-1-DELETE": True, 451 | } 452 | 453 | res = self.client.post("/inlines/new/", data, follow=True) 454 | self.assertEqual(len(res.context_data["form"].errors), 1) 455 | self.assertEqual(len(res.context_data["inlines"][0].errors[0]), 2) 456 | 457 | def test_view_object_is_none_after_failed_validation_for_createview(self): 458 | # We are testing that view.object = None even if the form validates 459 | # but one of the inline formsets does not. 460 | data = { 461 | "name": "Dummy Order", 462 | "items-TOTAL_FORMS": "2", 463 | "items-INITIAL_FORMS": "0", 464 | "items-MAX_NUM_FORMS": "", 465 | "items-0-name": "Test Item 1", 466 | "items-0-sku": "", 467 | "items-0-price": "", 468 | "items-0-status": 0, 469 | "items-1-name": "", 470 | "items-1-sku": "", 471 | "items-1-price": "", 472 | "items-1-status": "", 473 | "items-1-DELETE": True, 474 | "extra_views_tests-tag-content_type-object_id-TOTAL_FORMS": 2, 475 | "extra_views_tests-tag-content_type-object_id-INITIAL_FORMS": 0, 476 | "extra_views_tests-tag-content_type-object_id-MAX_NUM_FORMS": "", 477 | "extra_views_tests-tag-content_type-object_id-0-name": "Test", 478 | "extra_views_tests-tag-content_type-object_id-1-DELETE": True, 479 | } 480 | 481 | res = self.client.post("/inlines/new/", data, follow=True) 482 | self.assertEqual(len(res.context_data["form"].errors), 0) 483 | self.assertEqual(len(res.context_data["inlines"][0].errors[0]), 2) 484 | self.assertEqual(res.context_data["view"].object, None) 485 | 486 | def test_update(self): 487 | order = Order(name="Dummy Order") 488 | order.save() 489 | 490 | item_ids = [] 491 | for i in range(2): 492 | item = Item( 493 | name="Item %i" % i, 494 | sku=str(i) * 13, 495 | price=D("9.99"), 496 | order=order, 497 | status=0, 498 | ) 499 | item.save() 500 | item_ids.append(item.id) 501 | 502 | tag = Tag(name="Test", content_object=order) 503 | tag.save() 504 | 505 | res = self.client.get("/inlines/{}/".format(order.id)) 506 | 507 | self.assertEqual(res.status_code, 200) 508 | order = Order.objects.get(id=order.id) 509 | 510 | self.assertEqual(2, order.items.count()) 511 | self.assertEqual("Item 0", order.items.all()[0].name) 512 | 513 | data = { 514 | "name": "Dummy Order", 515 | "items-TOTAL_FORMS": "4", 516 | "items-INITIAL_FORMS": "2", 517 | "items-MAX_NUM_FORMS": "", 518 | "items-0-name": "Bubble Bath", 519 | "items-0-sku": "1234567890123", 520 | "items-0-price": D("9.99"), 521 | "items-0-status": 0, 522 | "items-0-id": item_ids[0], 523 | "items-1-name": "Bubble Bath", 524 | "items-1-sku": "1234567890123", 525 | "items-1-price": D("9.99"), 526 | "items-1-status": 0, 527 | "items-1-id": item_ids[1], 528 | "items-2-name": "Bubble Bath", 529 | "items-2-sku": "1234567890123", 530 | "items-2-price": D("9.99"), 531 | "items-2-status": 0, 532 | "items-3-DELETE": True, 533 | "extra_views_tests-tag-content_type-object_id-TOTAL_FORMS": 3, 534 | "extra_views_tests-tag-content_type-object_id-INITIAL_FORMS": 1, 535 | "extra_views_tests-tag-content_type-object_id-MAX_NUM_FORMS": "", 536 | "extra_views_tests-tag-content_type-object_id-0-name": "Test", 537 | "extra_views_tests-tag-content_type-object_id-0-id": tag.id, 538 | "extra_views_tests-tag-content_type-object_id-0-DELETE": True, 539 | "extra_views_tests-tag-content_type-object_id-1-name": "Test 2", 540 | "extra_views_tests-tag-content_type-object_id-2-name": "Test 3", 541 | } 542 | 543 | res = self.client.post("/inlines/{}/".format(order.id), data) 544 | self.assertEqual(res.status_code, 302) 545 | # Test that the returned url is the same as the instances absolute url. 546 | self.assertEqual(res.url, order.get_absolute_url()) 547 | 548 | order = Order.objects.get(id=order.id) 549 | 550 | self.assertEqual(3, order.items.count()) 551 | self.assertEqual(2, Tag.objects.count()) 552 | self.assertEqual("Bubble Bath", order.items.all()[0].name) 553 | 554 | def test_parent_instance_saved_in_form_save(self): 555 | order = Order(name="Dummy Order") 556 | order.save() 557 | 558 | data = { 559 | "name": "Dummy Order", 560 | "items-TOTAL_FORMS": "0", 561 | "items-INITIAL_FORMS": "0", 562 | "items-MAX_NUM_FORMS": "", 563 | "extra_views_tests-tag-content_type-object_id-TOTAL_FORMS": "0", 564 | "extra_views_tests-tag-content_type-object_id-INITIAL_FORMS": "0", 565 | "extra_views_tests-tag-content_type-object_id-MAX_NUM_FORMS": "", 566 | } 567 | 568 | res = self.client.post("/inlines/{}/".format(order.id), data) 569 | self.assertEqual(res.status_code, 302) 570 | 571 | order = Order.objects.get(id=order.id) 572 | self.assertTrue(order.action_on_save) 573 | 574 | def test_url_arg(self): 575 | """ 576 | Regression test for #122: get_context_data should not be called with *args 577 | """ 578 | res = self.client.get("/inlines/123/new/") 579 | self.assertEqual(res.status_code, 200) 580 | 581 | 582 | class CalendarViewTests(TestCase): 583 | def test_create(self): 584 | event = Event(name="Test Event", date=datetime.date(2012, 1, 1)) 585 | event.save() 586 | 587 | res = self.client.get("/events/2012/jan/") 588 | self.assertEqual(res.status_code, 200) 589 | 590 | 591 | class SearchableListTests(TestCase): 592 | def setUp(self): 593 | order = Order(name="Dummy Order") 594 | order.save() 595 | Item.objects.create( 596 | sku="1A", 597 | name="test A", 598 | order=order, 599 | price=0, 600 | date_placed=datetime.date(2012, 1, 1), 601 | ) 602 | Item.objects.create( 603 | sku="1B", 604 | name="test B", 605 | order=order, 606 | price=0, 607 | date_placed=datetime.date(2012, 2, 1), 608 | ) 609 | Item.objects.create( 610 | sku="C", 611 | name="test", 612 | order=order, 613 | price=0, 614 | date_placed=datetime.date(2012, 3, 1), 615 | ) 616 | 617 | def test_search(self): 618 | res = self.client.get("/searchable/", data={"q": "1A test"}) 619 | self.assertEqual(res.status_code, 200) 620 | self.assertEqual(1, len(res.context_data["object_list"])) 621 | 622 | res = self.client.get("/searchable/", data={"q": "1Atest"}) 623 | self.assertEqual(res.status_code, 200) 624 | self.assertEqual(0, len(res.context_data["object_list"])) 625 | 626 | # date search 627 | res = self.client.get("/searchable/", data={"q": "01.01.2012"}) 628 | self.assertEqual(res.status_code, 200) 629 | self.assertEqual(1, len(res.context_data["object_list"])) 630 | 631 | res = self.client.get("/searchable/", data={"q": "02.01.2012"}) 632 | self.assertEqual(res.status_code, 200) 633 | self.assertEqual(0, len(res.context_data["object_list"])) 634 | 635 | # search query provided by view's get_search_query method 636 | res = self.client.get( 637 | "/searchable/predefined_query/", data={"q": "idoesntmatter"} 638 | ) 639 | self.assertEqual(res.status_code, 200) 640 | self.assertEqual(1, len(res.context_data["object_list"])) 641 | 642 | # exact search query 643 | res = self.client.get("/searchable/exact_query/", data={"q": "test"}) 644 | self.assertEqual(res.status_code, 200) 645 | self.assertEqual(1, len(res.context_data["object_list"])) 646 | 647 | # search query consists only of spaces 648 | res = self.client.get("/searchable/", data={"q": " "}) 649 | self.assertEqual(res.status_code, 200) 650 | self.assertEqual(3, len(res.context_data["object_list"])) 651 | 652 | # wrong lookup 653 | try: 654 | self.assertRaises( 655 | self.client.get("/searchable/wrong_lookup/", data={"q": "test"}) 656 | ) 657 | error = False 658 | except ValueError: 659 | error = True 660 | self.assertTrue(error) 661 | 662 | 663 | class SortableViewTest(TestCase): 664 | def setUp(self): 665 | order = Order(name="Dummy Order") 666 | order.save() 667 | Item.objects.create(sku="1A", name="test A", order=order, price=0) 668 | Item.objects.create(sku="1B", name="test B", order=order, price=0) 669 | 670 | def test_sort(self): 671 | res = self.client.get("/sortable/fields/") 672 | self.assertEqual(res.status_code, 200) 673 | self.assertFalse(res.context_data["sort_helper"].is_sorted_by_name()) 674 | 675 | asc_url = res.context_data["sort_helper"].get_sort_query_by_name_asc() 676 | res = self.client.get("/sortable/fields/%s" % asc_url) 677 | self.assertEqual(res.context_data["object_list"][0].name, "test A") 678 | self.assertEqual(res.context_data["object_list"][1].name, "test B") 679 | self.assertTrue(res.context_data["sort_helper"].is_sorted_by_name()) 680 | 681 | desc_url = res.context_data["sort_helper"].get_sort_query_by_name_desc() 682 | res = self.client.get("/sortable/fields/%s" % desc_url) 683 | self.assertEqual(res.context_data["object_list"][0].name, "test B") 684 | self.assertEqual(res.context_data["object_list"][1].name, "test A") 685 | self.assertTrue(res.context_data["sort_helper"].is_sorted_by_name()) 686 | # reversed sorting 687 | sort_url = res.context_data["sort_helper"].get_sort_query_by_name() 688 | res = self.client.get("/sortable/fields/%s" % sort_url) 689 | self.assertEqual(res.context_data["object_list"][0].name, "test A") 690 | sort_url = res.context_data["sort_helper"].get_sort_query_by_name() 691 | res = self.client.get("/sortable/fields/%s" % sort_url) 692 | self.assertEqual(res.context_data["object_list"][0].name, "test B") 693 | # can't use fields and aliases in same time 694 | self.assertRaises( 695 | ImproperlyConfigured, 696 | lambda: self.client.get("/sortable/fields_and_aliases/"), 697 | ) 698 | # check that aliases included in params 699 | res = self.client.get("/sortable/aliases/") 700 | self.assertIn( 701 | "o=by_name", res.context_data["sort_helper"].get_sort_query_by_by_name() 702 | ) 703 | self.assertIn( 704 | "o=by_sku", res.context_data["sort_helper"].get_sort_query_by_by_sku() 705 | ) 706 | -------------------------------------------------------------------------------- /extra_views_tests/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import path 2 | from django.views.generic import TemplateView 3 | 4 | from .formsets import AddressFormSet 5 | from .views import ( 6 | AddressFormSetView, 7 | AddressFormSetViewKwargs, 8 | AddressFormSetViewNamed, 9 | EventCalendarView, 10 | FormAndFormSetOverrideView, 11 | ItemModelFormSetExcludeView, 12 | ItemModelFormSetView, 13 | OrderCreateNamedView, 14 | OrderCreateView, 15 | OrderItemFormSetView, 16 | OrderTagsView, 17 | OrderUpdateView, 18 | PagedModelFormSetView, 19 | SearchableItemListView, 20 | SortableItemListView, 21 | ) 22 | 23 | urlpatterns = [ 24 | path("formset/simple/", AddressFormSetView.as_view()), 25 | path("formset/simple/named/", AddressFormSetViewNamed.as_view()), 26 | path("formset/simple/kwargs/", AddressFormSetViewKwargs.as_view()), 27 | path( 28 | "formset/simple_redirect/", 29 | AddressFormSetView.as_view(success_url="/formset/simple_redirect/valid/"), 30 | ), 31 | path( 32 | "formset/simple_redirect/valid/", 33 | TemplateView.as_view(template_name="extra_views/success.html"), 34 | ), 35 | path("formset/custom/", AddressFormSetView.as_view(formset_class=AddressFormSet)), 36 | path("modelformset/simple/", ItemModelFormSetView.as_view()), 37 | path("modelformset/exclude/", ItemModelFormSetExcludeView.as_view()), 38 | path("modelformset/custom/", FormAndFormSetOverrideView.as_view()), 39 | path("modelformset/paged/", PagedModelFormSetView.as_view()), 40 | path("inlineformset//", OrderItemFormSetView.as_view()), 41 | path("inlines//new/", OrderCreateView.as_view()), 42 | path("inlines/new/", OrderCreateView.as_view()), 43 | path("inlines/new/named/", OrderCreateNamedView.as_view()), 44 | path("inlines//", OrderUpdateView.as_view()), 45 | path("genericinlineformset//", OrderTagsView.as_view()), 46 | path("sortable//", SortableItemListView.as_view()), 47 | path("events///", EventCalendarView.as_view()), 48 | path("searchable/", SearchableItemListView.as_view()), 49 | path( 50 | "searchable/predefined_query/", 51 | SearchableItemListView.as_view(define_query=True), 52 | ), 53 | path("searchable/exact_query/", SearchableItemListView.as_view(exact_query=True)), 54 | path("searchable/wrong_lookup/", SearchableItemListView.as_view(wrong_lookup=True)), 55 | ] 56 | -------------------------------------------------------------------------------- /extra_views_tests/views.py: -------------------------------------------------------------------------------- 1 | from django.views import generic 2 | 3 | from extra_views import ( 4 | CalendarMonthView, 5 | CreateWithInlinesView, 6 | FormSetSuccessMessageMixin, 7 | FormSetView, 8 | InlineFormSetFactory, 9 | InlineFormSetView, 10 | ModelFormSetView, 11 | NamedFormsetsMixin, 12 | SearchableListMixin, 13 | SortableListMixin, 14 | SuccessMessageMixin, 15 | UpdateWithInlinesView, 16 | ) 17 | from extra_views.generic import GenericInlineFormSetFactory, GenericInlineFormSetView 18 | 19 | from .forms import AddressForm, ItemForm, OrderForm 20 | from .formsets import BaseArticleFormSet 21 | from .models import Event, Item, Order, Tag 22 | 23 | 24 | class AddressFormSetView(FormSetSuccessMessageMixin, FormSetView): 25 | form_class = AddressForm 26 | template_name = "extra_views/address_formset.html" 27 | success_message = "Formset objects were created successfully!" 28 | 29 | 30 | class AddressFormSetViewNamed(NamedFormsetsMixin, AddressFormSetView): 31 | inlines_names = ["AddressFormset"] 32 | 33 | 34 | class AddressFormSetViewKwargs(FormSetView): 35 | # Used for testing class level kwargs 36 | form_class = AddressForm 37 | template_name = "extra_views/address_formset.html" 38 | formset_kwargs = {"auto_id": "id_test_%s", "form_kwargs": {"empty_permitted": True}} 39 | factory_kwargs = {"max_num": 27} 40 | prefix = "test_prefix" 41 | initial = [{"name": "address1"}] 42 | 43 | 44 | class AddressFormSetViewFormKwargs(FormSetView): 45 | form_class = AddressForm 46 | template_name = "extra_views/address_formset.html" 47 | formset_kwargs = {"form_kwargs": {"empty_permitted": True}} 48 | factory_kwargs = {"max_num": 27} 49 | form_kwargs = {"label_suffix": ":"} 50 | 51 | 52 | class ItemModelFormSetView(ModelFormSetView): 53 | model = Item 54 | fields = ["name", "sku", "price", "order", "status"] 55 | template_name = "extra_views/item_formset.html" 56 | 57 | 58 | class ItemModelFormSetExcludeView(ModelFormSetView): 59 | model = Item 60 | exclude = ["sku", "price"] 61 | template_name = "extra_views/item_formset.html" 62 | 63 | 64 | class FormAndFormSetOverrideView(ModelFormSetView): 65 | model = Item 66 | form_class = ItemForm 67 | formset_class = BaseArticleFormSet 68 | template_name = "extra_views/item_formset.html" 69 | 70 | 71 | class OrderItemFormSetView(InlineFormSetView): 72 | model = Order 73 | fields = ["name", "sku", "price", "order", "status"] 74 | inline_model = Item 75 | template_name = "extra_views/inline_formset.html" 76 | 77 | 78 | class PagedModelFormSetView(ModelFormSetView): 79 | paginate_by = 2 80 | model = Item 81 | template_name = "extra_views/paged_formset.html" 82 | 83 | 84 | class ItemsInline(InlineFormSetFactory): 85 | model = Item 86 | fields = ["name", "sku", "price", "order", "status"] 87 | 88 | 89 | class TagsInline(GenericInlineFormSetFactory): 90 | model = Tag 91 | fields = ["name"] 92 | 93 | 94 | class OrderCreateView(SuccessMessageMixin, CreateWithInlinesView): 95 | model = Order 96 | fields = ["name"] 97 | context_object_name = "order" 98 | inlines = [ItemsInline, TagsInline] 99 | template_name = "extra_views/order_and_items.html" 100 | success_message = "Order %(name)s was created successfully!" 101 | 102 | def form_valid(self, form): 103 | response = super().form_valid(form) 104 | # Update the response url to indicate that form_valid was called 105 | response["Location"] += "?form_valid_called=1" 106 | return response 107 | 108 | 109 | class OrderCreateNamedView(NamedFormsetsMixin, OrderCreateView): 110 | inlines_names = ["Items", "Tags"] 111 | 112 | 113 | class OrderUpdateView(UpdateWithInlinesView): 114 | model = Order 115 | form_class = OrderForm 116 | inlines = [ItemsInline, TagsInline] 117 | template_name = "extra_views/order_and_items.html" 118 | 119 | 120 | class OrderTagsView(GenericInlineFormSetView): 121 | model = Order 122 | inline_model = Tag 123 | template_name = "extra_views/inline_formset.html" 124 | initial = [{"name": "test_tag_name"}] 125 | 126 | 127 | class EventCalendarView(CalendarMonthView): 128 | template_name = "extra_views/event_calendar_month.html" 129 | model = Event 130 | month_format = "%b" 131 | date_field = "date" 132 | 133 | 134 | class SearchableItemListView(SearchableListMixin, generic.ListView): 135 | template_name = "extra_views/item_list.html" 136 | search_fields = ["name", "sku"] 137 | search_date_fields = ["date_placed"] 138 | model = Item 139 | define_query = False 140 | exact_query = False 141 | wrong_lookup = False 142 | 143 | def get_search_query(self): 144 | if self.define_query: 145 | return "test B" 146 | else: 147 | return super().get_search_query() 148 | 149 | def get(self, request, *args, **kwargs): 150 | if self.exact_query: 151 | self.search_fields = [("name", "iexact"), "sku"] 152 | elif self.wrong_lookup: 153 | self.search_fields = [("name", "gte"), "sku"] 154 | return super().get(request, *args, **kwargs) 155 | 156 | 157 | class SortableItemListView(SortableListMixin, generic.ListView): 158 | template_name = "extra_views/sortable_item_list.html" 159 | sort_fields = ["name", "sku"] 160 | model = Item 161 | 162 | def get(self, request, *args, **kwargs): 163 | if kwargs["flag"] == "fields_and_aliases": 164 | self.sort_fields_aliases = [("name", "by_name"), ("sku", "by_sku")] 165 | elif kwargs["flag"] == "aliases": 166 | self.sort_fields_aliases = [("name", "by_name"), ("sku", "by_sku")] 167 | self.sort_fields = [] 168 | return super().get(request, *args, **kwargs) 169 | -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | if __name__ == "__main__": 6 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "extra_views_tests.settings") 7 | try: 8 | from django.core.management import execute_from_command_line 9 | except ImportError as exc: 10 | raise ImportError( 11 | "Couldn't import Django. Are you sure it's installed and " 12 | "available on your PYTHONPATH environment variable? Did you " 13 | "forget to activate a virtual environment?" 14 | ) from exc 15 | execute_from_command_line(sys.argv) 16 | -------------------------------------------------------------------------------- /readthedocs.yaml: -------------------------------------------------------------------------------- 1 | version: 2 2 | 3 | build: 4 | os: ubuntu-22.04 5 | tools: 6 | python: "3.11" 7 | 8 | sphinx: 9 | configuration: docs/conf.py -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bdist_wheel] 2 | universal = 1 3 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | from setuptools import setup 4 | 5 | # get version without importing 6 | with open("extra_views/__init__.py", "rb") as f: 7 | VERSION = str(re.search('__version__ = "(.+?)"', f.read().decode("utf-8")).group(1)) 8 | 9 | setup( 10 | name="django-extra-views", 11 | version=VERSION, 12 | url="https://github.com/AndrewIngram/django-extra-views", 13 | install_requires=["Django >=2.1"], 14 | python_requires=">=3.5", 15 | description="Extra class-based views for Django", 16 | long_description=open("README.rst", "r").read(), 17 | license="MIT", 18 | author="Andrew Ingram", 19 | author_email="andy@andrewingram.net", 20 | packages=["extra_views", "extra_views.contrib"], 21 | classifiers=[ 22 | "Development Status :: 3 - Alpha", 23 | "Environment :: Web Environment", 24 | "Framework :: Django", 25 | "Intended Audience :: Developers", 26 | "License :: OSI Approved :: MIT License", 27 | "Programming Language :: Python", 28 | "Programming Language :: Python :: 3", 29 | ], 30 | ) 31 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py38-django{22,30,31,32,40,41,42} 3 | py39-django{22,30,31,32,40,41,42} 4 | py310-django{32,40,41,42,50,51,52} 5 | py311-django{41,42,50,51,52} 6 | py312-django{42,50,51,52,master} 7 | py313-django{51,52,master} 8 | black 9 | isort 10 | flake8 11 | docs 12 | 13 | [gh-actions] 14 | python = 15 | 3.8: py38 16 | 3.9: py39 17 | 3.10: py310 18 | 3.11: py311 19 | 3.12: py312 20 | 3.13: py313, docs 21 | 22 | [testenv] 23 | setenv = 24 | PYTHONPATH = {toxinidir} 25 | PYTHONWARNINGS = all 26 | PYTEST_ADDOPTS = --cov --cov-fail-under=85 --cov-report=xml --cov-report=term 27 | 28 | # The dash ahead of the command allows djangomaster to fail and still return 0 (success) 29 | commands = 30 | !djangomaster: pytest {posargs} 31 | djangomaster: -pytest {posargs} 32 | 33 | deps = 34 | django22: Django>=2.2,<2.3 35 | django30: Django>=3.0a1,<3.1 36 | django31: Django>=3.1,<3.2 37 | django32: Django>=3.2,<4.0 38 | django40: Django>=4.0,<4.1 39 | django41: Django>=4.1,<4.2 40 | django42: Django>=4.2,<5.0 41 | django50: Django>=5.0,<5.1 42 | django51: Django>=5.1,<5.2 43 | django52: Django>=5.2,<6.0 44 | djangomaster: https://github.com/django/django/archive/main.tar.gz 45 | pytest-django 46 | pytest-cov 47 | 48 | [testenv:black] 49 | skip_install = True 50 | deps = 51 | black 52 | commands = 53 | black {toxinidir} --check 54 | 55 | [testenv:isort] 56 | skip_install = True 57 | deps = 58 | isort 59 | commands = 60 | isort {toxinidir} --check-only 61 | 62 | [testenv:flake8] 63 | skip_install = True 64 | deps = 65 | flake8 66 | commands = 67 | flake8 {toxinidir} {posargs} 68 | 69 | [testenv:docs] 70 | allowlist_externals=make 71 | changedir = docs 72 | deps = 73 | sphinx 74 | commands = 75 | make html 76 | 77 | [pytest] 78 | DJANGO_SETTINGS_MODULE = extra_views_tests.settings 79 | python_files = tests.py test_*.py *_tests.py 80 | 81 | [coverage:run] 82 | branch = True 83 | source = extra_views 84 | 85 | [flake8] 86 | max-complexity = 10 87 | extend-exclude = extra_views_tests/migrations/, build/lib/, docs/conf.py, venv, .venv 88 | ignore = W191, W503, E203 89 | max-line-length = 88 90 | 91 | [isort] 92 | default_section = THIRDPARTY 93 | known_first_party = extra_views 94 | # black compatibility, as per 95 | # https://black.readthedocs.io/en/stable/the_black_code_style.html?highlight=.isort.cfg#how-black-wraps-lines 96 | multi_line_output = 3 97 | include_trailing_comma = True 98 | force_grid_wrap = 0 99 | use_parentheses = True 100 | line_length = 88 101 | --------------------------------------------------------------------------------