├── .coveragerc ├── .editorconfig ├── .github └── ISSUE_TEMPLATE.md ├── .gitignore ├── .travis.yml ├── AUTHORS.rst ├── CONTRIBUTING.rst ├── HISTORY.rst ├── LICENSE ├── MANIFEST.in ├── Makefile ├── README.rst ├── docs ├── Makefile ├── authors.rst ├── conf.py ├── contributing.rst ├── history.rst ├── index.rst ├── installation.rst ├── make.bat ├── readme.rst └── usage.rst ├── export_action ├── __init__.py ├── admin.py ├── introspection.py ├── locale │ ├── pt_BR │ │ └── LC_MESSAGES │ │ │ └── django.po │ ├── ru_RU │ │ └── LC_MESSAGES │ │ │ └── django.po │ └── zh_Hans │ │ └── LC_MESSAGES │ │ └── django.po ├── models.py ├── report.py ├── templates │ └── export_action │ │ ├── export.html │ │ ├── fields.html │ │ └── report_html.html ├── urls.py └── views.py ├── pytest.ini ├── requirements_dev.txt ├── requirements_test.txt ├── setup.cfg ├── setup.py ├── tests ├── __init__.py ├── admin.py ├── models.py ├── settings.py ├── test_export_action.py └── urls.py └── tox.ini /.coveragerc: -------------------------------------------------------------------------------- 1 | [run] 2 | branch = True 3 | data_file = .coverage 4 | parallel = False 5 | source = 6 | export_action 7 | omit = 8 | */migrations/* 9 | *test*.py 10 | tmp/* 11 | pytest_cov 12 | 13 | [report] 14 | exclude_lines = 15 | # Have to re-enable the standard pragma 16 | pragma: no cover 17 | 18 | # Don't complain about missing debug-only code: 19 | def __repr__ 20 | if self\.debug 21 | 22 | # Don't complain about default Django's code 23 | from django.shortcuts import render 24 | from django.contrib import admin 25 | 26 | # Don't complain if tests don't hit defensive assertion code: 27 | raise AssertionError 28 | raise NotImplementedError 29 | 30 | [html] 31 | directory = tmp/htmlcov 32 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # http://editorconfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | charset = utf-8 7 | end_of_line = lf 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | 11 | [*.{py,rst,ini}] 12 | indent_style = space 13 | indent_size = 4 14 | 15 | [*.{html,css,scss,json,yml}] 16 | indent_style = space 17 | indent_size = 2 18 | 19 | [*.md] 20 | trim_trailing_whitespace = false 21 | 22 | [Makefile] 23 | indent_style = tab 24 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | * Django Export Action version: 2 | * Django version: 3 | * Python version: 4 | * Operating System: 5 | 6 | ### Description 7 | 8 | Describe what you were trying to get done. 9 | Tell us what happened, what went wrong, and what you expected to happen. 10 | 11 | ### What I Did 12 | 13 | ``` 14 | Paste the command(s) you ran and the output. 15 | If there was a crash, please include the traceback here. 16 | ``` 17 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.py[cod] 2 | __pycache__ 3 | *.db 4 | 5 | # C extensions 6 | *.so 7 | 8 | # Packages 9 | *.egg 10 | *.egg-info 11 | dist 12 | build 13 | eggs 14 | parts 15 | bin 16 | var 17 | sdist 18 | develop-eggs 19 | .installed.cfg 20 | lib 21 | lib64 22 | tmp/ 23 | .cache/ 24 | 25 | # Installer logs 26 | pip-log.txt 27 | 28 | # Unit test / coverage reports 29 | .coverage* 30 | .tox 31 | nosetests.xml 32 | htmlcov 33 | 34 | # Translations 35 | *.mo 36 | 37 | # Editors 38 | .mr.developer.cfg 39 | .project 40 | .pydevproject 41 | .idea 42 | *.sublime-* 43 | 44 | # Complexity 45 | output/*.html 46 | output/*/index.html 47 | 48 | # Sphinx 49 | docs/_build 50 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | # Config file for automatic testing at travis-ci.org 2 | 3 | language: python 4 | 5 | python: 6 | - "3.5" 7 | - "3.4" 8 | - "2.7" 9 | 10 | before_install: 11 | - pip install -U pytest 12 | - pip install codecov 13 | - pip install -e . 14 | 15 | # command to install dependencies, e.g. pip install -r requirements.txt --use-mirrors 16 | install: pip install -r requirements_test.txt 17 | 18 | # command to run tests using coverage, e.g. python setup.py test 19 | script: py.test 20 | 21 | after_success: 22 | - codecov 23 | -------------------------------------------------------------------------------- /AUTHORS.rst: -------------------------------------------------------------------------------- 1 | ======= 2 | Credits 3 | ======= 4 | 5 | This project started as a fork of `django-admin-export`_. 6 | 7 | .. _django-admin-export: https://github.com/burke-software/django-admin-export 8 | 9 | Development Lead 10 | ---------------- 11 | 12 | * Fernando Macedo 13 | 14 | Contributors 15 | ------------ 16 | 17 | 18 | None yet. Why not be the first? 19 | 20 | 21 | Tools 22 | --------- 23 | 24 | Tools used in rendering this package: 25 | 26 | * Cookiecutter_ 27 | * `cookiecutter-djangopackage`_ 28 | 29 | .. _Cookiecutter: https://github.com/audreyr/cookiecutter 30 | .. _`cookiecutter-djangopackage`: https://github.com/pydanny/cookiecutter-djangopackage 31 | -------------------------------------------------------------------------------- /CONTRIBUTING.rst: -------------------------------------------------------------------------------- 1 | ============ 2 | Contributing 3 | ============ 4 | 5 | Contributions are welcome, and they are greatly appreciated! Every 6 | little bit helps, and credit will always be given. 7 | 8 | You can contribute in many ways: 9 | 10 | Types of Contributions 11 | ---------------------- 12 | 13 | Report Bugs 14 | ~~~~~~~~~~~ 15 | 16 | Report bugs at https://github.com/fgmacedo/django-export-action/issues. 17 | 18 | If you are reporting a bug, please include: 19 | 20 | * Your operating system name and version. 21 | * Any details about your local setup that might be helpful in troubleshooting. 22 | * Detailed steps to reproduce the bug. 23 | 24 | Fix Bugs 25 | ~~~~~~~~ 26 | 27 | Look through the GitHub issues for bugs. Anything tagged with "bug" 28 | is open to whoever wants to implement it. 29 | 30 | Implement Features 31 | ~~~~~~~~~~~~~~~~~~ 32 | 33 | Look through the GitHub issues for features. Anything tagged with "feature" 34 | is open to whoever wants to implement it. 35 | 36 | Write Documentation 37 | ~~~~~~~~~~~~~~~~~~~ 38 | 39 | Django Export Action could always use more documentation, whether as part of the 40 | official Django Export Action docs, in docstrings, or even on the web in blog posts, 41 | articles, and such. 42 | 43 | Submit Feedback 44 | ~~~~~~~~~~~~~~~ 45 | 46 | The best way to send feedback is to file an issue at https://github.com/fgmacedo/django-export-action/issues. 47 | 48 | If you are proposing a feature: 49 | 50 | * Explain in detail how it would work. 51 | * Keep the scope as narrow as possible, to make it easier to implement. 52 | * Remember that this is a volunteer-driven project, and that contributions 53 | are welcome :) 54 | 55 | Get Started! 56 | ------------ 57 | 58 | Ready to contribute? Here's how to set up `django-export-action` for local development. 59 | 60 | 1. Fork the `django-export-action` repo on GitHub. 61 | 2. Clone your fork locally:: 62 | 63 | $ git clone git@github.com:your_name_here/django-export-action.git 64 | 65 | 3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:: 66 | 67 | $ mkvirtualenv django-export-action 68 | $ cd django-export-action/ 69 | $ python setup.py develop 70 | 71 | 4. Create a branch for local development:: 72 | 73 | $ git checkout -b name-of-your-bugfix-or-feature 74 | 75 | Now you can make your changes locally. 76 | 77 | 5. When you're done making changes, check that your changes pass flake8 and the 78 | tests, including testing other Python versions with tox:: 79 | 80 | $ flake8 export_action tests 81 | $ python setup.py test 82 | $ tox 83 | 84 | To get flake8 and tox, just pip install them into your virtualenv. 85 | 86 | 6. Commit your changes and push your branch to GitHub:: 87 | 88 | $ git add . 89 | $ git commit -m "Your detailed description of your changes." 90 | $ git push origin name-of-your-bugfix-or-feature 91 | 92 | 7. Submit a pull request through the GitHub website. 93 | 94 | Pull Request Guidelines 95 | ----------------------- 96 | 97 | Before you submit a pull request, check that it meets these guidelines: 98 | 99 | 1. The pull request should include tests. 100 | 2. If the pull request adds functionality, the docs should be updated. Put 101 | your new functionality into a function with a docstring, and add the 102 | feature to the list in README.rst. 103 | 3. The pull request should work for Python 2.6, 2.7, and 3.3, and for PyPy. Check 104 | https://travis-ci.org/fgmacedo/django-export-action/pull_requests 105 | and make sure that the tests pass for all supported Python versions. 106 | 107 | Tips 108 | ---- 109 | 110 | To run a subset of tests:: 111 | 112 | $ python -m unittest tests.test_export_action 113 | -------------------------------------------------------------------------------- /HISTORY.rst: -------------------------------------------------------------------------------- 1 | .. :changelog: 2 | 3 | History 4 | ------- 5 | 6 | 0.1.0 (2016-09-29) 7 | ++++++++++++++++++ 8 | 9 | * First release on PyPI. 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | MIT License 3 | 4 | Copyright (c) 2016, Fernando Macedo 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | 8 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | 10 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include AUTHORS.rst 2 | include CONTRIBUTING.rst 3 | include HISTORY.rst 4 | include LICENSE 5 | include README.rst 6 | recursive-include export_action *.html *.png *.gif *js *.css *jpg *jpeg *svg *py *.po *.mo 7 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: clean-pyc clean-build docs help 2 | .DEFAULT_GOAL := help 3 | define BROWSER_PYSCRIPT 4 | import os, webbrowser, sys 5 | try: 6 | from urllib import pathname2url 7 | except: 8 | from urllib.request import pathname2url 9 | 10 | webbrowser.open("file://" + pathname2url(os.path.abspath(sys.argv[1]))) 11 | endef 12 | export BROWSER_PYSCRIPT 13 | BROWSER := python -c "$$BROWSER_PYSCRIPT" 14 | 15 | help: 16 | @perl -nle'print $& if m{^[a-zA-Z_-]+:.*?## .*$$}' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-25s\033[0m %s\n", $$1, $$2}' 17 | 18 | clean: clean-build clean-pyc 19 | 20 | clean-build: ## remove build artifacts 21 | rm -fr build/ 22 | rm -fr dist/ 23 | rm -fr *.egg-info 24 | 25 | clean-pyc: ## remove Python file artifacts 26 | find . -name '*.pyc' -exec rm -f {} + 27 | find . -name '*.pyo' -exec rm -f {} + 28 | find . -name '*~' -exec rm -f {} + 29 | 30 | lint: ## check style with flake8 31 | flake8 export_action tests 32 | 33 | test: ## run tests quickly with the default Python 34 | python runtests.py tests 35 | 36 | test-all: ## run tests on every Python version with tox 37 | tox 38 | 39 | coverage: ## check code coverage quickly with the default Python 40 | coverage run --source export_action runtests.py tests 41 | coverage report -m 42 | coverage html 43 | open htmlcov/index.html 44 | 45 | docs: ## generate Sphinx HTML documentation, including API docs 46 | rm -f docs/django-export-action.rst 47 | rm -f docs/modules.rst 48 | sphinx-apidoc -o docs/ export_action 49 | $(MAKE) -C docs clean 50 | $(MAKE) -C docs html 51 | $(BROWSER) docs/_build/html/index.html 52 | 53 | release: clean ## package and upload a release 54 | python setup.py sdist upload 55 | python setup.py bdist_wheel upload 56 | 57 | sdist: clean ## package 58 | python setup.py sdist 59 | ls -l dist 60 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ============================= 2 | Django Export Action 3 | ============================= 4 | 5 | .. image:: https://badge.fury.io/py/django-export-action.svg 6 | :target: https://badge.fury.io/py/django-export-action 7 | 8 | .. image:: https://travis-ci.org/fgmacedo/django-export-action.svg?branch=master 9 | :target: https://travis-ci.org/fgmacedo/django-export-action 10 | 11 | .. image:: https://img.shields.io/codecov/c/github/fgmacedo/django-export-action/master.svg?label=branch%20coverage 12 | :target: https://codecov.io/github/fgmacedo/django-export-action 13 | 14 | 15 | Generic export action for Django's Admin 16 | 17 | Quickstart 18 | ---------- 19 | 20 | Install Django Export Action:: 21 | 22 | pip install django-export-action 23 | 24 | Include it on INSTALLED_APPS:: 25 | 26 | 'export_action', 27 | 28 | Add to urls: 29 | 30 | .. code-block:: python 31 | 32 | url(r'^export_action/', include("export_action.urls", namespace="export_action")), 33 | 34 | Usage 35 | ----- 36 | 37 | Go to any admin page, select fields, then select the export to xls action. Then 38 | check off any fields you want to export. 39 | 40 | Features 41 | -------- 42 | 43 | * Generic action to enable export data from Admin. 44 | * Automatic traversal of model relations. 45 | * Selection of fields to export. 46 | * Can export to XSLx, CSV and HTML. 47 | 48 | Running Tests 49 | -------------- 50 | 51 | Does the code actually work? 52 | 53 | :: 54 | 55 | source /bin/activate 56 | (myenv) $ pip install -r requirements_test.txt 57 | (myenv) $ py.test 58 | 59 | 60 | Security 61 | -------- 62 | 63 | This project assumes staff users are trusted. There may be ways for users to 64 | manipulate this project to get more data access than they should have. 65 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | 49 | clean: 50 | rm -rf $(BUILDDIR)/* 51 | 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | dirhtml: 58 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 59 | @echo 60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 61 | 62 | singlehtml: 63 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 64 | @echo 65 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 66 | 67 | pickle: 68 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 69 | @echo 70 | @echo "Build finished; now you can process the pickle files." 71 | 72 | json: 73 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 74 | @echo 75 | @echo "Build finished; now you can process the JSON files." 76 | 77 | htmlhelp: 78 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 79 | @echo 80 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 81 | ".hhp project file in $(BUILDDIR)/htmlhelp." 82 | 83 | qthelp: 84 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 85 | @echo 86 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 87 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 88 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/complexity.qhcp" 89 | @echo "To view the help file:" 90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/complexity.qhc" 91 | 92 | devhelp: 93 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 94 | @echo 95 | @echo "Build finished." 96 | @echo "To view the help file:" 97 | @echo "# mkdir -p $$HOME/.local/share/devhelp/complexity" 98 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/complexity" 99 | @echo "# devhelp" 100 | 101 | epub: 102 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 103 | @echo 104 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 105 | 106 | latex: 107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 108 | @echo 109 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 110 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 111 | "(use \`make latexpdf' here to do that automatically)." 112 | 113 | latexpdf: 114 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 115 | @echo "Running LaTeX files through pdflatex..." 116 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 117 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 118 | 119 | latexpdfja: 120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 121 | @echo "Running LaTeX files through platex and dvipdfmx..." 122 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 123 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 124 | 125 | text: 126 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 127 | @echo 128 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 129 | 130 | man: 131 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 132 | @echo 133 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 134 | 135 | texinfo: 136 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 137 | @echo 138 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 139 | @echo "Run \`make' in that directory to run these through makeinfo" \ 140 | "(use \`make info' here to do that automatically)." 141 | 142 | info: 143 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 144 | @echo "Running Texinfo files through makeinfo..." 145 | make -C $(BUILDDIR)/texinfo info 146 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 147 | 148 | gettext: 149 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 150 | @echo 151 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 152 | 153 | changes: 154 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 155 | @echo 156 | @echo "The overview file is in $(BUILDDIR)/changes." 157 | 158 | linkcheck: 159 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 160 | @echo 161 | @echo "Link check complete; look for any errors in the above output " \ 162 | "or in $(BUILDDIR)/linkcheck/output.txt." 163 | 164 | doctest: 165 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 166 | @echo "Testing of doctests in the sources finished, look at the " \ 167 | "results in $(BUILDDIR)/doctest/output.txt." 168 | 169 | xml: 170 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 171 | @echo 172 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 173 | 174 | pseudoxml: 175 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 176 | @echo 177 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 178 | -------------------------------------------------------------------------------- /docs/authors.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../AUTHORS.rst 2 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # complexity documentation build configuration file, created by 4 | # sphinx-quickstart on Tue Jul 9 22:26:36 2013. 5 | # 6 | # This file is execfile()d with the current directory set to its containing dir. 7 | # 8 | # Note that not all possible configuration values are present in this 9 | # autogenerated file. 10 | # 11 | # All configuration values have a default; values that are commented out 12 | # serve to show the default. 13 | 14 | import sys, os 15 | 16 | # If extensions (or modules to document with autodoc) are in another directory, 17 | # add these directories to sys.path here. If the directory is relative to the 18 | # documentation root, use os.path.abspath to make it absolute, like shown here. 19 | #sys.path.insert(0, os.path.abspath('.')) 20 | 21 | cwd = os.getcwd() 22 | parent = os.path.dirname(cwd) 23 | sys.path.append(parent) 24 | 25 | import export_action 26 | 27 | # -- General configuration ----------------------------------------------------- 28 | 29 | # If your documentation needs a minimal Sphinx version, state it here. 30 | #needs_sphinx = '1.0' 31 | 32 | # Add any Sphinx extension module names here, as strings. They can be extensions 33 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 34 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] 35 | 36 | # Add any paths that contain templates here, relative to this directory. 37 | templates_path = ['_templates'] 38 | 39 | # The suffix of source filenames. 40 | source_suffix = '.rst' 41 | 42 | # The encoding of source files. 43 | #source_encoding = 'utf-8-sig' 44 | 45 | # The master toctree document. 46 | master_doc = 'index' 47 | 48 | # General information about the project. 49 | project = u'Django Export Action' 50 | copyright = u'2016, Fernando Macedo' 51 | 52 | # The version info for the project you're documenting, acts as replacement for 53 | # |version| and |release|, also used in various other places throughout the 54 | # built documents. 55 | # 56 | # The short X.Y version. 57 | version = export_action.__version__ 58 | # The full version, including alpha/beta/rc tags. 59 | release = export_action.__version__ 60 | 61 | # The language for content autogenerated by Sphinx. Refer to documentation 62 | # for a list of supported languages. 63 | #language = None 64 | 65 | # There are two options for replacing |today|: either, you set today to some 66 | # non-false value, then it is used: 67 | #today = '' 68 | # Else, today_fmt is used as the format for a strftime call. 69 | #today_fmt = '%B %d, %Y' 70 | 71 | # List of patterns, relative to source directory, that match files and 72 | # directories to ignore when looking for source files. 73 | exclude_patterns = ['_build'] 74 | 75 | # The reST default role (used for this markup: `text`) to use for all documents. 76 | #default_role = None 77 | 78 | # If true, '()' will be appended to :func: etc. cross-reference text. 79 | #add_function_parentheses = True 80 | 81 | # If true, the current module name will be prepended to all description 82 | # unit titles (such as .. function::). 83 | #add_module_names = True 84 | 85 | # If true, sectionauthor and moduleauthor directives will be shown in the 86 | # output. They are ignored by default. 87 | #show_authors = False 88 | 89 | # The name of the Pygments (syntax highlighting) style to use. 90 | pygments_style = 'sphinx' 91 | 92 | # A list of ignored prefixes for module index sorting. 93 | #modindex_common_prefix = [] 94 | 95 | # If true, keep warnings as "system message" paragraphs in the built documents. 96 | #keep_warnings = False 97 | 98 | 99 | # -- Options for HTML output --------------------------------------------------- 100 | 101 | # The theme to use for HTML and HTML Help pages. See the documentation for 102 | # a list of builtin themes. 103 | html_theme = 'default' 104 | 105 | # Theme options are theme-specific and customize the look and feel of a theme 106 | # further. For a list of options available for each theme, see the 107 | # documentation. 108 | #html_theme_options = {} 109 | 110 | # Add any paths that contain custom themes here, relative to this directory. 111 | #html_theme_path = [] 112 | 113 | # The name for this set of Sphinx documents. If None, it defaults to 114 | # " v documentation". 115 | #html_title = None 116 | 117 | # A shorter title for the navigation bar. Default is the same as html_title. 118 | #html_short_title = None 119 | 120 | # The name of an image file (relative to this directory) to place at the top 121 | # of the sidebar. 122 | #html_logo = None 123 | 124 | # The name of an image file (within the static path) to use as favicon of the 125 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 126 | # pixels large. 127 | #html_favicon = None 128 | 129 | # Add any paths that contain custom static files (such as style sheets) here, 130 | # relative to this directory. They are copied after the builtin static files, 131 | # so a file named "default.css" will overwrite the builtin "default.css". 132 | html_static_path = ['_static'] 133 | 134 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 135 | # using the given strftime format. 136 | #html_last_updated_fmt = '%b %d, %Y' 137 | 138 | # If true, SmartyPants will be used to convert quotes and dashes to 139 | # typographically correct entities. 140 | #html_use_smartypants = True 141 | 142 | # Custom sidebar templates, maps document names to template names. 143 | #html_sidebars = {} 144 | 145 | # Additional templates that should be rendered to pages, maps page names to 146 | # template names. 147 | #html_additional_pages = {} 148 | 149 | # If false, no module index is generated. 150 | #html_domain_indices = True 151 | 152 | # If false, no index is generated. 153 | #html_use_index = True 154 | 155 | # If true, the index is split into individual pages for each letter. 156 | #html_split_index = False 157 | 158 | # If true, links to the reST sources are added to the pages. 159 | #html_show_sourcelink = True 160 | 161 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 162 | #html_show_sphinx = True 163 | 164 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 165 | #html_show_copyright = True 166 | 167 | # If true, an OpenSearch description file will be output, and all pages will 168 | # contain a tag referring to it. The value of this option must be the 169 | # base URL from which the finished HTML is served. 170 | #html_use_opensearch = '' 171 | 172 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 173 | #html_file_suffix = None 174 | 175 | # Output file base name for HTML help builder. 176 | htmlhelp_basename = 'django-export-actiondoc' 177 | 178 | 179 | # -- Options for LaTeX output -------------------------------------------------- 180 | 181 | latex_elements = { 182 | # The paper size ('letterpaper' or 'a4paper'). 183 | #'papersize': 'letterpaper', 184 | 185 | # The font size ('10pt', '11pt' or '12pt'). 186 | #'pointsize': '10pt', 187 | 188 | # Additional stuff for the LaTeX preamble. 189 | #'preamble': '', 190 | } 191 | 192 | # Grouping the document tree into LaTeX files. List of tuples 193 | # (source start file, target name, title, author, documentclass [howto/manual]). 194 | latex_documents = [ 195 | ('index', 'django-export-action.tex', u'Django Export Action Documentation', 196 | u'Fernando Macedo', 'manual'), 197 | ] 198 | 199 | # The name of an image file (relative to this directory) to place at the top of 200 | # the title page. 201 | #latex_logo = None 202 | 203 | # For "manual" documents, if this is true, then toplevel headings are parts, 204 | # not chapters. 205 | #latex_use_parts = False 206 | 207 | # If true, show page references after internal links. 208 | #latex_show_pagerefs = False 209 | 210 | # If true, show URL addresses after external links. 211 | #latex_show_urls = False 212 | 213 | # Documents to append as an appendix to all manuals. 214 | #latex_appendices = [] 215 | 216 | # If false, no module index is generated. 217 | #latex_domain_indices = True 218 | 219 | 220 | # -- Options for manual page output -------------------------------------------- 221 | 222 | # One entry per manual page. List of tuples 223 | # (source start file, name, description, authors, manual section). 224 | man_pages = [ 225 | ('index', 'django-export-action', u'Django Export Action Documentation', 226 | [u'Fernando Macedo'], 1) 227 | ] 228 | 229 | # If true, show URL addresses after external links. 230 | #man_show_urls = False 231 | 232 | 233 | # -- Options for Texinfo output ------------------------------------------------ 234 | 235 | # Grouping the document tree into Texinfo files. List of tuples 236 | # (source start file, target name, title, author, 237 | # dir menu entry, description, category) 238 | texinfo_documents = [ 239 | ('index', 'django-export-action', u'Django Export Action Documentation', 240 | u'Fernando Macedo', 'django-export-action', 'One line description of project.', 241 | 'Miscellaneous'), 242 | ] 243 | 244 | # Documents to append as an appendix to all manuals. 245 | #texinfo_appendices = [] 246 | 247 | # If false, no module index is generated. 248 | #texinfo_domain_indices = True 249 | 250 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 251 | #texinfo_show_urls = 'footnote' 252 | 253 | # If true, do not generate a @detailmenu in the "Top" node's menu. 254 | #texinfo_no_detailmenu = False 255 | -------------------------------------------------------------------------------- /docs/contributing.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../CONTRIBUTING.rst 2 | -------------------------------------------------------------------------------- /docs/history.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../HISTORY.rst 2 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. complexity documentation master file, created by 2 | sphinx-quickstart on Tue Jul 9 22:26:36 2013. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to Django Export Action's documentation! 7 | ================================================================= 8 | 9 | Contents: 10 | 11 | .. toctree:: 12 | :maxdepth: 2 13 | 14 | readme 15 | installation 16 | usage 17 | contributing 18 | authors 19 | history 20 | -------------------------------------------------------------------------------- /docs/installation.rst: -------------------------------------------------------------------------------- 1 | ============ 2 | Installation 3 | ============ 4 | 5 | At the command line:: 6 | 7 | $ easy_install django-export-action 8 | 9 | Or, if you have virtualenvwrapper installed:: 10 | 11 | $ mkvirtualenv django-export-action 12 | $ pip install django-export-action 13 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 31 | echo. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. xml to make Docutils-native XML files 37 | echo. pseudoxml to make pseudoxml-XML files for display purposes 38 | echo. linkcheck to check all external links for integrity 39 | echo. doctest to run all doctests embedded in the documentation if enabled 40 | goto end 41 | ) 42 | 43 | if "%1" == "clean" ( 44 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 45 | del /q /s %BUILDDIR%\* 46 | goto end 47 | ) 48 | 49 | 50 | %SPHINXBUILD% 2> nul 51 | if errorlevel 9009 ( 52 | echo. 53 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 54 | echo.installed, then set the SPHINXBUILD environment variable to point 55 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 56 | echo.may add the Sphinx directory to PATH. 57 | echo. 58 | echo.If you don't have Sphinx installed, grab it from 59 | echo.http://sphinx-doc.org/ 60 | exit /b 1 61 | ) 62 | 63 | if "%1" == "html" ( 64 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 65 | if errorlevel 1 exit /b 1 66 | echo. 67 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 68 | goto end 69 | ) 70 | 71 | if "%1" == "dirhtml" ( 72 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 73 | if errorlevel 1 exit /b 1 74 | echo. 75 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 76 | goto end 77 | ) 78 | 79 | if "%1" == "singlehtml" ( 80 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 81 | if errorlevel 1 exit /b 1 82 | echo. 83 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 84 | goto end 85 | ) 86 | 87 | if "%1" == "pickle" ( 88 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 89 | if errorlevel 1 exit /b 1 90 | echo. 91 | echo.Build finished; now you can process the pickle files. 92 | goto end 93 | ) 94 | 95 | if "%1" == "json" ( 96 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 97 | if errorlevel 1 exit /b 1 98 | echo. 99 | echo.Build finished; now you can process the JSON files. 100 | goto end 101 | ) 102 | 103 | if "%1" == "htmlhelp" ( 104 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 105 | if errorlevel 1 exit /b 1 106 | echo. 107 | echo.Build finished; now you can run HTML Help Workshop with the ^ 108 | .hhp project file in %BUILDDIR%/htmlhelp. 109 | goto end 110 | ) 111 | 112 | if "%1" == "qthelp" ( 113 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 114 | if errorlevel 1 exit /b 1 115 | echo. 116 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 117 | .qhcp project file in %BUILDDIR%/qthelp, like this: 118 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\complexity.qhcp 119 | echo.To view the help file: 120 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\complexity.ghc 121 | goto end 122 | ) 123 | 124 | if "%1" == "devhelp" ( 125 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished. 129 | goto end 130 | ) 131 | 132 | if "%1" == "epub" ( 133 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 134 | if errorlevel 1 exit /b 1 135 | echo. 136 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 137 | goto end 138 | ) 139 | 140 | if "%1" == "latex" ( 141 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 142 | if errorlevel 1 exit /b 1 143 | echo. 144 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 145 | goto end 146 | ) 147 | 148 | if "%1" == "latexpdf" ( 149 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 150 | cd %BUILDDIR%/latex 151 | make all-pdf 152 | cd %BUILDDIR%/.. 153 | echo. 154 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 155 | goto end 156 | ) 157 | 158 | if "%1" == "latexpdfja" ( 159 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 160 | cd %BUILDDIR%/latex 161 | make all-pdf-ja 162 | cd %BUILDDIR%/.. 163 | echo. 164 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 165 | goto end 166 | ) 167 | 168 | if "%1" == "text" ( 169 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 170 | if errorlevel 1 exit /b 1 171 | echo. 172 | echo.Build finished. The text files are in %BUILDDIR%/text. 173 | goto end 174 | ) 175 | 176 | if "%1" == "man" ( 177 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 178 | if errorlevel 1 exit /b 1 179 | echo. 180 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 181 | goto end 182 | ) 183 | 184 | if "%1" == "texinfo" ( 185 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 186 | if errorlevel 1 exit /b 1 187 | echo. 188 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 189 | goto end 190 | ) 191 | 192 | if "%1" == "gettext" ( 193 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 194 | if errorlevel 1 exit /b 1 195 | echo. 196 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 197 | goto end 198 | ) 199 | 200 | if "%1" == "changes" ( 201 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 202 | if errorlevel 1 exit /b 1 203 | echo. 204 | echo.The overview file is in %BUILDDIR%/changes. 205 | goto end 206 | ) 207 | 208 | if "%1" == "linkcheck" ( 209 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 210 | if errorlevel 1 exit /b 1 211 | echo. 212 | echo.Link check complete; look for any errors in the above output ^ 213 | or in %BUILDDIR%/linkcheck/output.txt. 214 | goto end 215 | ) 216 | 217 | if "%1" == "doctest" ( 218 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 219 | if errorlevel 1 exit /b 1 220 | echo. 221 | echo.Testing of doctests in the sources finished, look at the ^ 222 | results in %BUILDDIR%/doctest/output.txt. 223 | goto end 224 | ) 225 | 226 | if "%1" == "xml" ( 227 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 228 | if errorlevel 1 exit /b 1 229 | echo. 230 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 231 | goto end 232 | ) 233 | 234 | if "%1" == "pseudoxml" ( 235 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 236 | if errorlevel 1 exit /b 1 237 | echo. 238 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 239 | goto end 240 | ) 241 | 242 | :end 243 | -------------------------------------------------------------------------------- /docs/readme.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../README.rst 2 | -------------------------------------------------------------------------------- /docs/usage.rst: -------------------------------------------------------------------------------- 1 | ======== 2 | Usage 3 | ======== 4 | 5 | To use Django Export Action in a project:: 6 | 7 | import export_action 8 | -------------------------------------------------------------------------------- /export_action/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = '0.1.1' 2 | -------------------------------------------------------------------------------- /export_action/admin.py: -------------------------------------------------------------------------------- 1 | import uuid 2 | from django.contrib import admin 3 | from django.contrib.contenttypes.models import ContentType 4 | from django.core.urlresolvers import reverse 5 | from django.http import HttpResponseRedirect 6 | from django.utils.translation import ugettext_lazy as _ 7 | 8 | 9 | def export_selected_objects(modeladmin, request, queryset): 10 | selected = list(queryset.values_list('id', flat=True)) 11 | ct = ContentType.objects.get_for_model(queryset.model) 12 | url = reverse("export_action:export") 13 | 14 | if len(selected) > 1000: 15 | session_key = "export_action_%s" % uuid.uuid4() 16 | request.session[session_key] = selected 17 | return HttpResponseRedirect("%s?ct=%s&session_key=%s" % (url, ct.pk, session_key)) 18 | else: 19 | return HttpResponseRedirect( 20 | "%s?ct=%s&ids=%s" % (url, ct.pk, ",".join(str(pk) for pk in selected))) 21 | 22 | 23 | export_selected_objects.short_description = _("Export selected items...") 24 | 25 | admin.site.add_action(export_selected_objects) 26 | -------------------------------------------------------------------------------- /export_action/introspection.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | from __future__ import unicode_literals, absolute_import 4 | 5 | from itertools import chain 6 | 7 | from django.contrib.contenttypes.models import ContentType 8 | from django.db.models.fields import FieldDoesNotExist 9 | 10 | 11 | def _get_field_by_name(model_class, field_name): 12 | """ 13 | Compatible with old API of model_class._meta.get_field_by_name(field_name) 14 | """ 15 | field = model_class._meta.get_field(field_name) 16 | return ( 17 | field, # field 18 | field.model, # model 19 | not field.auto_created or field.concrete, # direct 20 | field.many_to_many # m2m 21 | ) 22 | 23 | 24 | def _get_remote_field(field): 25 | """ 26 | Compatible with Django 1.8~1.10 ('related' was renamed to 'remote_field') 27 | """ 28 | if hasattr(field, 'remote_field'): 29 | return field.remote_field 30 | elif hasattr(field, 'related'): 31 | return field.related 32 | else: 33 | return None 34 | 35 | 36 | def _get_all_field_names(model): 37 | """ 38 | 100% compatible version of the old API of model._meta.get_all_field_names() 39 | From: https://docs.djangoproject.com/en/1.9/ref/models/meta/#migrating-from-the-old-api 40 | """ 41 | return list(set(chain.from_iterable( 42 | (field.name, field.attname) if hasattr(field, 'attname') else (field.name,) 43 | for field in model._meta.get_fields() 44 | # For complete backwards compatibility, you may want to exclude 45 | # GenericForeignKey from the results. 46 | if not (field.many_to_one and field.related_model is None) 47 | ))) 48 | 49 | 50 | def get_relation_fields_from_model(model_class): 51 | """ Get related fields (m2m, FK, and reverse FK) """ 52 | relation_fields = [] 53 | all_fields_names = _get_all_field_names(model_class) 54 | for field_name in all_fields_names: 55 | field, model, direct, m2m = _get_field_by_name(model_class, field_name) 56 | # get_all_field_names will return the same field 57 | # both with and without _id. Ignore the duplicate. 58 | if field_name[-3:] == '_id' and field_name[:-3] in all_fields_names: 59 | continue 60 | if m2m or not direct or _get_remote_field(field): 61 | field.field_name_override = field_name 62 | relation_fields += [field] 63 | return relation_fields 64 | 65 | 66 | def get_direct_fields_from_model(model_class): 67 | """ Direct, not m2m, not FK """ 68 | direct_fields = [] 69 | all_fields_names = _get_all_field_names(model_class) 70 | for field_name in all_fields_names: 71 | field, model, direct, m2m = _get_field_by_name(model_class, field_name) 72 | if direct and not m2m and not _get_remote_field(field): 73 | direct_fields += [field] 74 | return direct_fields 75 | 76 | 77 | def get_model_from_path_string(root_model, path): 78 | """ Return a model class for a related model 79 | root_model is the class of the initial model 80 | path is like foo__bar where bar is related to foo 81 | """ 82 | for path_section in path.split('__'): 83 | if path_section: 84 | try: 85 | field, model, direct, m2m = _get_field_by_name(root_model, path_section) 86 | except FieldDoesNotExist: 87 | return root_model 88 | if direct: 89 | if _get_remote_field(field): 90 | try: 91 | root_model = _get_remote_field(field).parent_model() 92 | except AttributeError: 93 | root_model = _get_remote_field(field).model 94 | else: 95 | if hasattr(field, 'related_model'): 96 | root_model = field.related_model 97 | else: 98 | root_model = field.model 99 | return root_model 100 | 101 | 102 | def get_fields(model_class, field_name='', path=''): 103 | """ Get fields and meta data from a model 104 | 105 | :param model_class: A django model class 106 | :param field_name: The field name to get sub fields from 107 | :param path: path of our field in format 108 | field_name__second_field_name__ect__ 109 | :returns: Returns fields and meta data about such fields 110 | fields: Django model fields 111 | properties: Any properties the model has 112 | path: Our new path 113 | :rtype: dict 114 | """ 115 | fields = get_direct_fields_from_model(model_class) 116 | app_label = model_class._meta.app_label 117 | 118 | if field_name != '': 119 | field, model, direct, m2m = _get_field_by_name(model_class, field_name) 120 | 121 | path += field_name 122 | path += '__' 123 | if direct: # Direct field 124 | try: 125 | new_model = _get_remote_field(field).parent_model 126 | except AttributeError: 127 | new_model = _get_remote_field(field).model 128 | else: # Indirect related field 129 | new_model = field.related_model 130 | 131 | fields = get_direct_fields_from_model(new_model) 132 | 133 | app_label = new_model._meta.app_label 134 | 135 | return { 136 | 'fields': fields, 137 | 'path': path, 138 | 'app_label': app_label, 139 | } 140 | 141 | 142 | def get_related_fields(model_class, field_name, path=""): 143 | """ Get fields for a given model """ 144 | if field_name: 145 | field, model, direct, m2m = _get_field_by_name(model_class, field_name) 146 | if direct: 147 | # Direct field 148 | try: 149 | new_model = _get_remote_field(field).parent_model() 150 | except AttributeError: 151 | new_model = _get_remote_field(field).model 152 | else: 153 | # Indirect related field 154 | if hasattr(field, 'related_model'): # Django>=1.8 155 | new_model = field.related_model 156 | else: 157 | new_model = field.model() 158 | 159 | path += field_name 160 | path += '__' 161 | else: 162 | new_model = model_class 163 | 164 | new_fields = get_relation_fields_from_model(new_model) 165 | model_ct = ContentType.objects.get_for_model(new_model) 166 | 167 | return (new_fields, model_ct, path) 168 | -------------------------------------------------------------------------------- /export_action/locale/pt_BR/LC_MESSAGES/django.po: -------------------------------------------------------------------------------- 1 | # Translation to pt_BR. 2 | # Copyright (C) 2016 3 | # This file is distributed under the same license as the PACKAGE package. 4 | # Fernando Macedo , 2016. 5 | # 6 | #, fuzzy 7 | msgid "" 8 | msgstr "" 9 | "Project-Id-Version: 0.4.0\n" 10 | "Report-Msgid-Bugs-To: \n" 11 | "POT-Creation-Date: 2016-10-03 16:10-0300\n" 12 | "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" 13 | "Last-Translator: Fernando Macedo \n" 14 | "Language-Team: LANGUAGE \n" 15 | "Language: pt-br\n" 16 | "MIME-Version: 1.0\n" 17 | "Content-Type: text/plain; charset=UTF-8\n" 18 | "Content-Transfer-Encoding: 8bit\n" 19 | "Plural-Forms: nplurals=2; plural=(n > 1);\n" 20 | 21 | #: admin.py:22 22 | msgid "Export selected items..." 23 | msgstr "Exportar itens selecionados..." 24 | 25 | #: templates/export_action/export.html:33 26 | msgid "Home" 27 | msgstr "Home" 28 | 29 | #: templates/export_action/export.html:38 30 | #: templates/export_action/export.html:44 31 | #: templates/export_action/export.html:78 32 | msgid "Export" 33 | msgstr "Exportar" 34 | 35 | #: templates/export_action/export.html:62 36 | msgid "Select all" 37 | msgstr "Selecionar todos" 38 | 39 | #: templates/export_action/export.html:71 40 | msgid "Format" 41 | msgstr "Formato" 42 | -------------------------------------------------------------------------------- /export_action/locale/ru_RU/LC_MESSAGES/django.po: -------------------------------------------------------------------------------- 1 | # SOME DESCRIPTIVE TITLE. 2 | # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER 3 | # This file is distributed under the same license as the PACKAGE package. 4 | # FIRST AUTHOR , YEAR. 5 | # 6 | msgid "" 7 | msgstr "" 8 | "Project-Id-Version: django-export-action\n" 9 | "Report-Msgid-Bugs-To: \n" 10 | "POT-Creation-Date: 2017-04-21 14:21+0300\n" 11 | "PO-Revision-Date: 2017-04-21 14:28+0300\n" 12 | "Last-Translator: 1 <1>\n" 13 | "Language-Team: \n" 14 | "MIME-Version: 1.0\n" 15 | "Content-Type: text/plain; charset=UTF-8\n" 16 | "Content-Transfer-Encoding: 8bit\n" 17 | "X-Generator: Poedit 1.5.7\n" 18 | "Language: ru\n" 19 | 20 | #: admin.py:22 21 | msgid "Export selected items..." 22 | msgstr "Экспортировать выделенные элементы" 23 | 24 | #: templates/export_action/export.html:33 25 | msgid "Home" 26 | msgstr "Начало" 27 | 28 | #: templates/export_action/export.html:38 29 | #: templates/export_action/export.html:44 30 | #: templates/export_action/export.html:79 31 | msgid "Export" 32 | msgstr "Экспортировать" 33 | 34 | #: templates/export_action/export.html:63 35 | msgid "Select all" 36 | msgstr "Выбрать все" 37 | 38 | #: templates/export_action/export.html:72 39 | msgid "Format" 40 | msgstr "Формат" 41 | -------------------------------------------------------------------------------- /export_action/locale/zh_Hans/LC_MESSAGES/django.po: -------------------------------------------------------------------------------- 1 | # SOME DESCRIPTIVE TITLE. 2 | # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER 3 | # This file is distributed under the same license as the PACKAGE package. 4 | # FIRST yxy , 2017. 5 | # 6 | msgid "" 7 | msgstr "" 8 | "Project-Id-Version: django-export-action\n" 9 | "Report-Msgid-Bugs-To: \n" 10 | "POT-Creation-Date: 2017-04-21 14:21+0300\n" 11 | "PO-Revision-Date: 2017-04-21 14:28+0300\n" 12 | "Last-Translator: 1 <1>\n" 13 | "Language-Team: \n" 14 | "MIME-Version: 1.0\n" 15 | "Content-Type: text/plain; charset=UTF-8\n" 16 | "Content-Transfer-Encoding: 8bit\n" 17 | "X-Generator: Poedit 1.5.7\n" 18 | "Language: ru\n" 19 | 20 | #: admin.py:22 21 | msgid "Export selected items..." 22 | msgstr "导出所选内容" 23 | 24 | #: templates/export_action/export.html:33 25 | msgid "Home" 26 | msgstr "主页" 27 | 28 | #: templates/export_action/export.html:38 29 | #: templates/export_action/export.html:44 30 | #: templates/export_action/export.html:79 31 | msgid "Export" 32 | msgstr "导出" 33 | 34 | #: templates/export_action/export.html:63 35 | msgid "Select all" 36 | msgstr "选择全部" 37 | 38 | #: templates/export_action/export.html:72 39 | msgid "Format" 40 | msgstr "文件格式" 41 | -------------------------------------------------------------------------------- /export_action/models.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | -------------------------------------------------------------------------------- /export_action/report.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | from __future__ import unicode_literals, absolute_import 4 | 5 | from collections import namedtuple 6 | from itertools import chain 7 | import csv 8 | import re 9 | 10 | from django.http import HttpResponse 11 | from django.utils.text import force_text 12 | from django.template.loader import render_to_string 13 | from django.utils import timezone 14 | 15 | from openpyxl.styles import Font 16 | from openpyxl.utils import get_column_letter 17 | from openpyxl.workbook import Workbook 18 | from openpyxl.writer.excel import save_virtual_workbook 19 | 20 | from django.utils.six import BytesIO, text_type 21 | 22 | from .introspection import get_model_from_path_string 23 | 24 | 25 | DisplayField = namedtuple("DisplayField", "path field") 26 | 27 | 28 | def generate_filename(title, ends_with): 29 | title = title.split('.')[0] 30 | title.replace(' ', '_') 31 | title += ('_' + timezone.now().strftime("%Y-%m-%d_%H%M")) 32 | if not title.endswith(ends_with): 33 | title += ends_with 34 | return title 35 | 36 | 37 | def _can_change_or_view(model, user): 38 | """ Return True iff `user` has either change or view permission 39 | for `model`. 40 | """ 41 | model_name = model._meta.model_name 42 | app_label = model._meta.app_label 43 | can_change = user.has_perm(app_label + '.change_' + model_name) 44 | can_view = user.has_perm(app_label + '.view_' + model_name) 45 | 46 | return can_change or can_view 47 | 48 | 49 | def report_to_list(queryset, display_fields, user): 50 | """ Create list from a report with all data filtering. 51 | 52 | queryset: initial queryset to generate results 53 | display_fields: list of field references or DisplayField models 54 | user: requesting user 55 | 56 | Returns list, message in case of issues. 57 | """ 58 | model_class = queryset.model 59 | objects = queryset 60 | message = "" 61 | 62 | if not _can_change_or_view(model_class, user): 63 | return [], 'Permission Denied' 64 | 65 | # Convert list of strings to DisplayField objects. 66 | new_display_fields = [] 67 | 68 | for display_field in display_fields: 69 | field_list = display_field.split('__') 70 | field = field_list[-1] 71 | path = '__'.join(field_list[:-1]) 72 | 73 | if path: 74 | path += '__' # Legacy format to append a __ here. 75 | 76 | df = DisplayField(path, field) 77 | new_display_fields.append(df) 78 | 79 | display_fields = new_display_fields 80 | 81 | # Display Values 82 | display_field_paths = [] 83 | 84 | for i, display_field in enumerate(display_fields): 85 | model = get_model_from_path_string(model_class, display_field.path) 86 | 87 | if not model or _can_change_or_view(model, user): 88 | display_field_key = display_field.path + display_field.field 89 | 90 | display_field_paths.append(display_field_key) 91 | 92 | else: 93 | message += 'Error: Permission denied on access to {0}.'.format( 94 | display_field.name 95 | ) 96 | 97 | values_list = objects.values_list(*display_field_paths) 98 | values_and_properties_list = [list(row) for row in values_list] 99 | 100 | return values_and_properties_list, message 101 | 102 | 103 | def build_sheet(data, ws, sheet_name='report', header=None, widths=None): 104 | first_row = 1 105 | column_base = 1 106 | 107 | ws.title = re.sub(r'\W+', '', sheet_name)[:30] 108 | if header: 109 | for i, header_cell in enumerate(header): 110 | cell = ws.cell(row=first_row, column=i + column_base) 111 | cell.value = header_cell 112 | cell.font = Font(bold=True) 113 | if widths: 114 | ws.column_dimensions[get_column_letter(i + 1)].width = widths[i] 115 | 116 | for row in data: 117 | for i in range(len(row)): 118 | item = row[i] 119 | # If item is a regular string 120 | if isinstance(item, str): 121 | # Change it to a unicode string 122 | try: 123 | row[i] = text_type(item) 124 | except UnicodeDecodeError: 125 | row[i] = text_type(item.decode('utf-8', 'ignore')) 126 | elif type(item) is dict: 127 | row[i] = text_type(item) 128 | try: 129 | ws.append(row) 130 | except ValueError as e: 131 | ws.append([e.message]) 132 | except: 133 | ws.append(['Unknown Error']) 134 | 135 | 136 | def list_to_workbook(data, title='report', header=None, widths=None): 137 | """ Create just a openpxl workbook from a list of data """ 138 | wb = Workbook() 139 | title = re.sub(r'\W+', '', title)[:30] 140 | 141 | if isinstance(data, dict): 142 | i = 0 143 | for sheet_name, sheet_data in data.items(): 144 | if i > 0: 145 | wb.create_sheet() 146 | ws = wb.worksheets[i] 147 | build_sheet( 148 | sheet_data, ws, sheet_name=sheet_name, header=header) 149 | i += 1 150 | else: 151 | ws = wb.worksheets[0] 152 | build_sheet(data, ws, header=header, widths=widths) 153 | return wb 154 | 155 | 156 | def build_xlsx_response(wb, title="report"): 157 | """ Take a workbook and return a xlsx file response """ 158 | title = generate_filename(title, '.xlsx') 159 | myfile = BytesIO() 160 | myfile.write(save_virtual_workbook(wb)) 161 | response = HttpResponse( 162 | myfile.getvalue(), 163 | content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') 164 | response['Content-Disposition'] = 'attachment; filename=%s' % title 165 | response['Content-Length'] = myfile.tell() 166 | return response 167 | 168 | 169 | def list_to_xlsx_response(data, title='report', header=None, 170 | widths=None): 171 | """ Make 2D list into a xlsx response for download 172 | data can be a 2d array or a dict of 2d arrays 173 | like {'sheet_1': [['A1', 'B1']]} 174 | """ 175 | wb = list_to_workbook(data, title, header, widths) 176 | return build_xlsx_response(wb, title=title) 177 | 178 | 179 | def list_to_csv_response(data, title='report', header=None, widths=None): 180 | """ Make 2D list into a csv response for download data. 181 | """ 182 | response = HttpResponse(content_type="text/csv; charset=UTF-8") 183 | cw = csv.writer(response) 184 | for row in chain([header] if header else [], data): 185 | cw.writerow([force_text(s).encode(response.charset) for s in row]) 186 | return response 187 | 188 | 189 | def list_to_html_response(data, title='', header=None): 190 | html = render_to_string('export_action/report_html.html', locals()) 191 | return HttpResponse(html) 192 | -------------------------------------------------------------------------------- /export_action/templates/export_action/export.html: -------------------------------------------------------------------------------- 1 | {% extends 'admin/base_site.html' %} 2 | {% load i18n admin_urls admin_static %} 3 | 4 | {% block extrahead %} 5 | {{ block.super }} 6 | 7 | 8 | 29 | {% endblock %} 30 | 31 | {% block breadcrumbs %} 32 | 40 | {% endblock %} 41 | 42 | 43 | {% block content %} 44 |

{% trans "Export" %} {{ opts.verbose_name_plural }} ({{ queryset.count }})

45 |

46 | {% for object in queryset|slice:":10" %} 47 | {{ object }} 48 | {% if not forloop.last %},{% endif %} 49 | {% endfor %} 50 | {% if queryset.count > 10 %}...{% endif %} 51 |

52 | 53 |
54 |
55 |
56 | {% csrf_token %} 57 | 58 | 59 | 62 | 65 | 66 | 67 | {% include "export_action/fields.html" %} 68 |
60 | 61 | 63 | 64 |
69 |
70 |
71 |
72 | 79 | 80 |
81 |
82 | 83 | {% endblock %} 84 | -------------------------------------------------------------------------------- /export_action/templates/export_action/fields.html: -------------------------------------------------------------------------------- 1 | {% if table %}{% endif %} 2 | {% if field_name %} 3 | 4 | 5 | 6 | {% endif %} 7 | 8 | 9 | {% for field in fields %} 10 | 11 | 18 | 25 | 26 | {% endfor %} 27 | 28 | {% for field in related_fields %} 29 | 30 | 32 | 45 | 46 | {% endfor %} 47 | {% if table %}
{{ field_name }}
12 | 17 | 19 | {% if field.verbose_name %} 20 | {{ field.verbose_name }} 21 | {% else %} 22 | {{ field }} 23 | {% endif %} 24 |
31 | 33 | 36 | {% if field.verbose_name %} 37 | {{ field.verbose_name }} 38 | [{{ field.description }}] 39 | {% else %} 40 | {{ field.get_accessor_name }} 41 | {% endif %} 42 | → 43 | 44 |
{% endif %} 48 | -------------------------------------------------------------------------------- /export_action/templates/export_action/report_html.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {{ title }} 6 | 7 | 8 |

{{ title }}

9 | 10 | {% if header %} 11 | {% for h in header %}{% endfor %}{% endif %} 12 | 13 | {% for datum in data %} 14 | {% for cell in datum %}{% endfor %} 15 | {% endfor %} 16 | 17 |
{{ h }}
{{ cell|linebreaksbr }}
18 | 19 | 20 | -------------------------------------------------------------------------------- /export_action/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import url 2 | from django.contrib.admin.views.decorators import staff_member_required 3 | from .views import AdminExport 4 | 5 | view = staff_member_required(AdminExport.as_view()) 6 | 7 | urlpatterns = [ 8 | url(r'^export/$', view, name="export"), 9 | ] 10 | -------------------------------------------------------------------------------- /export_action/views.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | from __future__ import unicode_literals, absolute_import 4 | 5 | from django.contrib import admin 6 | from django.contrib.contenttypes.models import ContentType 7 | from django.views.generic import TemplateView 8 | 9 | 10 | from . import introspection 11 | from . import report 12 | 13 | 14 | class AdminExport(TemplateView): 15 | 16 | """ Get fields from a particular model """ 17 | template_name = 'export_action/export.html' 18 | 19 | def get_queryset(self, model_class): 20 | if self.request.GET.get("session_key"): 21 | ids = self.request.session[self.request.GET["session_key"]] 22 | else: 23 | ids = self.request.GET['ids'].split(',') 24 | try: 25 | model_admin = admin.site._registry[model_class] 26 | except KeyError: 27 | raise ValueError("Model %r not registered with admin" % model_class) 28 | queryset = model_admin.get_queryset(self.request).filter(pk__in=ids) 29 | return queryset 30 | 31 | def get_model_class(self): 32 | model_class = ContentType.objects.get(id=self.request.GET['ct']).model_class() 33 | return model_class 34 | 35 | def get_context_data(self, **kwargs): 36 | context = super(AdminExport, self).get_context_data(**kwargs) 37 | field_name = self.request.GET.get('field', '') 38 | model_class = self.get_model_class() 39 | queryset = self.get_queryset(model_class) 40 | path = self.request.GET.get('path', '') 41 | context['opts'] = model_class._meta 42 | context['queryset'] = queryset 43 | context['model_ct'] = self.request.GET['ct'] 44 | context['related_fields'] = introspection.get_relation_fields_from_model(model_class) 45 | context.update(introspection.get_fields(model_class, field_name, path)) 46 | return context 47 | 48 | def post(self, request, **kwargs): 49 | context = self.get_context_data(**kwargs) 50 | fields = [] 51 | for field_name, value in request.POST.items(): 52 | if value == "on": 53 | fields.append(field_name) 54 | data_list, message = report.report_to_list( 55 | context['queryset'], 56 | fields, 57 | self.request.user, 58 | ) 59 | format = request.POST.get("__format") 60 | if format == "html": 61 | return report.list_to_html_response(data_list, header=fields) 62 | elif format == "csv": 63 | return report.list_to_csv_response(data_list, header=fields) 64 | else: 65 | return report.list_to_xlsx_response(data_list, header=fields) 66 | 67 | def get(self, request, *args, **kwargs): 68 | if request.GET.get("related", request.POST.get("related")): # Dispatch to the other view 69 | return AdminExportRelated.as_view()(request=self.request) 70 | return super(AdminExport, self).get(request, *args, **kwargs) 71 | 72 | 73 | class AdminExportRelated(TemplateView): 74 | template_name = 'export_action/fields.html' 75 | 76 | def get(self, request, **kwargs): 77 | context = self.get_context_data(**kwargs) 78 | model_class = ContentType.objects.get(id=self.request.GET['model_ct']).model_class() 79 | field_name = request.GET['field'] 80 | path = request.GET['path'] 81 | field_data = introspection.get_fields(model_class, field_name, path) 82 | context['related_fields'], model_ct, context['path'] = introspection.get_related_fields( 83 | model_class, field_name, path 84 | ) 85 | context['model_ct'] = model_ct.id 86 | context['field_name'] = field_name 87 | context['table'] = True 88 | context.update(field_data) 89 | return self.render_to_response(context) 90 | -------------------------------------------------------------------------------- /pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | addopts = --pyargs --cache-clear --cov-config .coveragerc 3 | DJANGO_SETTINGS_MODULE=tests.settings 4 | -------------------------------------------------------------------------------- /requirements_dev.txt: -------------------------------------------------------------------------------- 1 | # test 2 | -r requirements_test.txt 3 | Django==1.11.5 4 | tox==2.8.1 5 | 6 | # docs 7 | Sphinx==1.6.3 8 | 9 | # build / deploy 10 | PyYAML==3.12 11 | wheel==0.29.0 12 | bumpversion==0.5.3 13 | cryptography==2.0.3 14 | pip==9.0.1 15 | -------------------------------------------------------------------------------- /requirements_test.txt: -------------------------------------------------------------------------------- 1 | pytest==3.2.5 2 | pytest-cov==2.5.1 3 | pytest-django==3.1.2 4 | pytest-flake8==0.8.1 5 | pytest-sugar==0.9.0 6 | pytest-watch==4.1.0 7 | python-decouple==3.1 8 | 9 | mixer==5.6.6 10 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bumpversion] 2 | current_version = 0.1.1 3 | commit = True 4 | tag = True 5 | 6 | [bumpversion:file:setup.py] 7 | 8 | [bumpversion:file:export_action/__init__.py] 9 | 10 | [wheel] 11 | universal = 1 12 | 13 | [flake8] 14 | max-line-length = 99 15 | exclude = .git/*,.tox/*,docs/*,dist/*,build/*,tests/migrations/* 16 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | import os 4 | import sys 5 | 6 | try: 7 | from setuptools import setup 8 | except ImportError: 9 | from distutils.core import setup 10 | 11 | version = '0.1.1' 12 | 13 | if sys.argv[-1] == 'publish': 14 | try: 15 | import wheel 16 | print("Wheel version: ", wheel.__version__) 17 | except ImportError: 18 | print('Wheel library missing. Please run "pip install wheel"') 19 | sys.exit() 20 | os.system('python setup.py sdist upload') 21 | os.system('python setup.py bdist_wheel upload') 22 | sys.exit() 23 | 24 | if sys.argv[-1] == 'tag': 25 | print("Tagging the version on git:") 26 | os.system("git tag -a %s -m 'version %s'" % (version, version)) 27 | os.system("git push --tags") 28 | sys.exit() 29 | 30 | readme = open('README.rst').read() 31 | history = open('HISTORY.rst').read().replace('.. :changelog:', '') 32 | 33 | setup( 34 | name='django-export-action', 35 | version=version, 36 | description="""Generic export action for Django's Admin""", 37 | long_description=readme + '\n\n' + history, 38 | author='Fernando Macedo', 39 | author_email='fgmacedo@gmail.com', 40 | url='https://github.com/fgmacedo/django-export-action', 41 | packages=[ 42 | 'export_action', 43 | ], 44 | include_package_data=True, 45 | install_requires=['openpyxl'], 46 | license="MIT", 47 | zip_safe=False, 48 | keywords='django-export-action', 49 | classifiers=[ 50 | 'Development Status :: 3 - Alpha', 51 | 'Framework :: Django', 52 | 'Framework :: Django :: 1.8', 53 | 'Framework :: Django :: 1.9', 54 | 'Framework :: Django :: 1.10', 55 | 'Framework :: Django :: 1.11', 56 | 'Intended Audience :: Developers', 57 | 'License :: OSI Approved :: BSD License', 58 | 'Natural Language :: English', 59 | 'Programming Language :: Python :: 2', 60 | 'Programming Language :: Python :: 2.7', 61 | 'Programming Language :: Python :: 3', 62 | 'Programming Language :: Python :: 3.4', 63 | 'Programming Language :: Python :: 3.5', 64 | 'Programming Language :: Python :: 3.6', 65 | ], 66 | ) 67 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fgmacedo/django-export-action/215fecb9044d22e3ae19d86c3b220041a11fad07/tests/__init__.py -------------------------------------------------------------------------------- /tests/admin.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | from __future__ import unicode_literals 3 | 4 | from django.contrib import admin 5 | 6 | from .models import Publication, Reporter, Article, Tag 7 | 8 | 9 | @admin.register(Publication) 10 | class PublicationAdmin(admin.ModelAdmin): 11 | pass 12 | 13 | 14 | @admin.register(Reporter) 15 | class ReporterAdmin(admin.ModelAdmin): 16 | pass 17 | 18 | 19 | @admin.register(Article) 20 | class ArticleAdmin(admin.ModelAdmin): 21 | pass 22 | 23 | 24 | @admin.register(Tag) 25 | class TagAdmin(admin.ModelAdmin): 26 | pass 27 | -------------------------------------------------------------------------------- /tests/models.py: -------------------------------------------------------------------------------- 1 | # -- encoding: UTF-8 -- 2 | from django.db import models 3 | from django.utils.encoding import python_2_unicode_compatible 4 | 5 | 6 | @python_2_unicode_compatible 7 | class Publication(models.Model): 8 | title = models.CharField(max_length=30) 9 | 10 | def __str__(self): 11 | return self.title 12 | 13 | class Meta: 14 | ordering = ('pk',) 15 | 16 | 17 | @python_2_unicode_compatible 18 | class Reporter(models.Model): 19 | first_name = models.CharField(max_length=30) 20 | last_name = models.CharField(max_length=30) 21 | email = models.EmailField() 22 | 23 | def __str__(self): 24 | return "%s %s" % (self.first_name, self.last_name) 25 | 26 | 27 | @python_2_unicode_compatible 28 | class Tag(models.Model): 29 | name = models.CharField(max_length=30) 30 | 31 | def __str__(self): 32 | return self.name 33 | 34 | class Meta: 35 | ordering = ('name',) 36 | 37 | 38 | @python_2_unicode_compatible 39 | class Article(models.Model): 40 | STATUS = ( 41 | (1, 'Draft'), 42 | (2, 'Revision'), 43 | (3, 'Published'), 44 | ) 45 | 46 | headline = models.CharField(max_length=100) 47 | publications = models.ManyToManyField(Publication) 48 | tags = models.ManyToManyField(Tag, through='ArticleTag') 49 | reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) 50 | status = models.IntegerField(choices=STATUS, default=1) 51 | 52 | def __str__(self): 53 | return self.headline 54 | 55 | class Meta: 56 | ordering = ('headline',) 57 | 58 | @property 59 | def contact(self): 60 | return self.reporter.email 61 | 62 | 63 | @python_2_unicode_compatible 64 | class ArticleTag(models.Model): 65 | tag = models.ForeignKey(Tag) 66 | article = models.ForeignKey(Article) 67 | 68 | created_on = models.DateTimeField('created on', auto_now_add=True) 69 | 70 | def __str__(self): 71 | return "{} on {}".format(self.tag, self.article) 72 | 73 | class Meta: 74 | ordering = ('created_on',) 75 | -------------------------------------------------------------------------------- /tests/settings.py: -------------------------------------------------------------------------------- 1 | # -- encoding: UTF-8 -- 2 | 3 | from decouple import config 4 | 5 | SECRET_KEY = "hi" 6 | DEBUG = config('DEBUG', default=False, cast=bool) 7 | 8 | ALLOWED_HOSTS = ['*'] 9 | 10 | DATABASES = { 11 | "default": dict( 12 | ENGINE='django.db.backends.sqlite3', 13 | NAME=config('DB_NAME', default=':memory:'), 14 | ) 15 | } 16 | 17 | INSTALLED_APPS = ( 18 | 'django.contrib.admin', 19 | 'django.contrib.auth', 20 | 'django.contrib.contenttypes', 21 | 'django.contrib.sessions', 22 | 'django.contrib.messages', 23 | 'django.contrib.staticfiles', 24 | 'export_action', 25 | 'tests', 26 | ) 27 | 28 | MIDDLEWARE_CLASSES = ( 29 | 'django.contrib.sessions.middleware.SessionMiddleware', 30 | 'django.middleware.common.CommonMiddleware', 31 | 'django.middleware.csrf.CsrfViewMiddleware', 32 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 33 | 'django.contrib.messages.middleware.MessageMiddleware', 34 | ) 35 | 36 | ROOT_URLCONF = 'tests.urls' 37 | 38 | STATIC_URL = '/static/' 39 | 40 | TEMPLATES = [ 41 | { 42 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 43 | 'DIRS': [], 44 | 'APP_DIRS': True, 45 | 'OPTIONS': { 46 | 'context_processors': [ 47 | 'django.template.context_processors.debug', 48 | 'django.template.context_processors.request', 49 | 'django.contrib.auth.context_processors.auth', 50 | 'django.contrib.messages.context_processors.messages', 51 | ], 52 | }, 53 | }, 54 | ] 55 | -------------------------------------------------------------------------------- /tests/test_export_action.py: -------------------------------------------------------------------------------- 1 | # -- encoding: UTF-8 -- 2 | 3 | from django.contrib.contenttypes.models import ContentType 4 | from django.core.urlresolvers import reverse 5 | from django.utils.http import urlencode 6 | 7 | import pytest 8 | from mixer.backend.django import mixer 9 | 10 | from export_action import report 11 | 12 | from .models import Publication, Reporter, Article, ArticleTag, Tag 13 | 14 | 15 | @pytest.mark.django_db 16 | @pytest.mark.parametrize('output_name', ['html', 'csv']) 17 | def test_AdminExport_list_to_method_response_should_return_200(admin_user, output_name): 18 | mixer.cycle(3).blend(Publication) 19 | data = report.report_to_list(Publication.objects.all(), ['title'], admin_user) 20 | 21 | method = getattr(report, 'list_to_{}_response'.format(output_name)) 22 | res = method(data) 23 | assert res.status_code == 200 24 | 25 | 26 | @pytest.mark.django_db 27 | @pytest.mark.parametrize('output_format', ['html', 'csv', 'xls']) 28 | def test_AdminExport_post_should_return_200(admin_client, output_format): 29 | mixer.cycle(3).blend(Publication) 30 | 31 | params = { 32 | 'ct': ContentType.objects.get_for_model(Publication).pk, 33 | 'ids': ','.join(repr(pk) for pk in Publication.objects.values_list('pk', flat=True)) 34 | } 35 | data = { 36 | "title": "on", 37 | "__format": output_format, 38 | } 39 | url = "{}?{}".format(reverse('export_action:export'), urlencode(params)) 40 | response = admin_client.post(url, data=data) 41 | assert response.status_code == 200 42 | 43 | 44 | @pytest.mark.django_db 45 | def test_AdminExport_get_should_return_200(admin_client): 46 | mixer.cycle(3).blend(Publication) 47 | 48 | params = { 49 | 'ct': ContentType.objects.get_for_model(Publication).pk, 50 | 'ids': ','.join(repr(pk) for pk in Publication.objects.values_list('pk', flat=True)) 51 | } 52 | url = "{}?{}".format(reverse('export_action:export'), urlencode(params)) 53 | response = admin_client.get(url) 54 | assert response.status_code == 200 55 | 56 | 57 | @pytest.mark.django_db 58 | def test_AdminExport_with_related_get_should_return_200(admin_client): 59 | reporter = mixer.blend(Reporter) 60 | mixer.cycle(3).blend(Article, reporter=reporter) 61 | 62 | params = { 63 | 'related': True, 64 | 'model_ct': ContentType.objects.get_for_model(Article).pk, 65 | 'field': 'reporter', 66 | 'path': 'reporter.first_name', 67 | } 68 | url = "{}?{}".format(reverse('export_action:export'), urlencode(params)) 69 | response = admin_client.get(url) 70 | assert response.status_code == 200 71 | 72 | 73 | @pytest.mark.django_db 74 | def test_export_with_related_of_indirect_field_get_should_return_200(admin_client): 75 | reporter = mixer.blend(Reporter) 76 | mixer.cycle(3).blend(Article, reporter=reporter) 77 | 78 | params = { 79 | 'related': True, 80 | 'model_ct': ContentType.objects.get_for_model(Article).pk, 81 | 'field': 'articletag', 82 | 'path': 'articletag.id', 83 | } 84 | url = "{}?{}".format(reverse('export_action:export'), urlencode(params)) 85 | response = admin_client.get(url) 86 | assert response.status_code == 200 87 | 88 | 89 | @pytest.mark.django_db 90 | def test_AdminExport_with_unregistered_model_should_raise_ValueError(admin_client): 91 | article = mixer.blend(Article) 92 | 93 | mixer.cycle(3).blend(ArticleTag, article=article) 94 | 95 | params = { 96 | 'ct': ContentType.objects.get_for_model(ArticleTag).pk, 97 | 'ids': ','.join(repr(pk) for pk in ArticleTag.objects.values_list('pk', flat=True)) 98 | } 99 | url = "{}?{}".format(reverse('export_action:export'), urlencode(params)) 100 | 101 | with pytest.raises(ValueError): 102 | admin_client.get(url) 103 | 104 | 105 | @pytest.mark.django_db 106 | def test_admin_action_should_redirect_to_export_view(admin_client): 107 | objects = mixer.cycle(3).blend(Publication) 108 | 109 | ids = [repr(obj.pk) for obj in objects] 110 | data = { 111 | "action": "export_selected_objects", 112 | "_selected_action": ids, 113 | } 114 | url = reverse('admin:tests_publication_changelist') 115 | response = admin_client.post(url, data=data) 116 | 117 | expected_url = "{}?ct={ct}&ids={ids}".format( 118 | reverse('export_action:export'), 119 | ct=ContentType.objects.get_for_model(Publication).pk, 120 | ids=','.join(ids) 121 | ) 122 | assert response.status_code == 302 123 | assert response.url.endswith(expected_url) 124 | 125 | 126 | @pytest.mark.django_db 127 | def test_admin_action_should_redirect_to_export_view_without_ids_for_large_queries(admin_client): 128 | objects = mixer.cycle(1001).blend(Publication) 129 | 130 | ids = [obj.pk for obj in objects[:50]] 131 | data = { 132 | "action": "export_selected_objects", 133 | "_selected_action": ids, 134 | "select_across": ids, 135 | } 136 | url = reverse('admin:tests_publication_changelist') 137 | response = admin_client.post(url, data=data) 138 | 139 | assert response.status_code == 302 140 | assert 'session_key' in response.url 141 | 142 | session_key = response.url[response.url.index('session_key=') + len('session_key='):] 143 | session_ids = admin_client.session[session_key] 144 | assert session_ids == [obj.pk for obj in objects] 145 | 146 | 147 | @pytest.mark.django_db 148 | @pytest.mark.parametrize('output_format', ['html', 'csv', 'xls']) 149 | def test_export_with_related_should_return_200(admin_client, output_format): 150 | publications = mixer.cycle(5).blend(Publication) 151 | reporter = mixer.blend(Reporter) 152 | tag = mixer.blend(Tag, name='python') 153 | articles = mixer.cycle(3).blend(Article, reporter=reporter, publications=publications) 154 | for article in articles: 155 | mixer.blend(ArticleTag, tag=tag, article=article) 156 | 157 | params = { 158 | 'ct': ContentType.objects.get_for_model(Article).pk, 159 | 'ids': ','.join(repr(pk) for pk in Article.objects.values_list('pk', flat=True)) 160 | } 161 | data = { 162 | 'id': 'on', 163 | 'headline': 'on', 164 | 'reporter__last_name': 'on', 165 | 'reporter__email': 'on', 166 | 'reporter__id': 'on', 167 | 'reporter__first_name': 'on', 168 | 'publications__id': 'on', 169 | 'articletag__id': 'on', 170 | 'publications__title': 'on', 171 | "__format": output_format, 172 | } 173 | url = "{}?{}".format(reverse('export_action:export'), urlencode(params)) 174 | response = admin_client.post(url, data=data) 175 | assert response.status_code == 200 176 | assert response.content 177 | 178 | assert Article.objects.first().publications.count() == 5 179 | assert Article.objects.first().tags.count() == 1 180 | assert Article.objects.first().reporter == reporter 181 | 182 | url = reverse('admin:tests_publication_changelist') 183 | response = admin_client.get(url) 184 | assert response.status_code == 200 185 | 186 | url = reverse('admin:tests_article_changelist') 187 | response = admin_client.get(url) 188 | assert response.status_code == 200 189 | 190 | for article in articles: 191 | url = reverse('admin:tests_article_change', args=[article.pk]) 192 | response = admin_client.get(url) 193 | assert response.status_code == 200 194 | -------------------------------------------------------------------------------- /tests/urls.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | from __future__ import unicode_literals 3 | 4 | from django.conf.urls import url, include 5 | from django.contrib import admin 6 | 7 | urlpatterns = [ 8 | url(r'^admin/', admin.site.urls), 9 | url(r'^export_action/', include("export_action.urls", namespace="export_action")), 10 | ] 11 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = 3 | py{27,34,35,36}-django{18,19,110,111} 4 | 5 | [travis] 6 | python = 7 | 3.6: py36 8 | 3.5: py35 9 | 3.4: py34 10 | 2.7: py27 11 | 12 | [testenv] 13 | setenv = 14 | PYTHONPATH = {toxinidir} 15 | DJANGO_SETTINGS_MODULE = tests.settings 16 | deps = 17 | django18: Django>=1.8,<1.9 18 | django19: Django>=1.9,<1.10 19 | django110: Django>=1.10,<1.11 20 | django111: Django>=1.11,<1.12 21 | -r{toxinidir}/requirements_test.txt 22 | commands = 23 | pip install -U pip 24 | py.test --basetemp={envtmpdir} --flake8 --cov 25 | 26 | basepython = 27 | py36: python3.6 28 | py35: python3.5 29 | py34: python3.4 30 | py27: python2.7 31 | --------------------------------------------------------------------------------