pax_global_header00006660000000000000000000000064140010647770014520gustar00rootroot0000000000000052 comment=e40a2deff11c4e7d4c9dbefcdf08a10352d628fa wtforms-components-0.10.5/000077500000000000000000000000001400106477700154675ustar00rootroot00000000000000wtforms-components-0.10.5/.gitignore000066400000000000000000000004031400106477700174540ustar00rootroot00000000000000*.py[co] # Packages *.egg *.egg-info dist build eggs parts bin var sdist develop-eggs .installed.cfg # Installer logs pip-log.txt # Unit test / coverage reports .coverage .tox #Translations *.mo #Mr Developer .mr.developer.cfg # Built docs docs/_build/ wtforms-components-0.10.5/.isort.cfg000066400000000000000000000002351400106477700173660ustar00rootroot00000000000000[settings] known_standard_library=cgi known_first_party=wtforms_components,tests line_length=79 multi_line_output=3 not_skip=__init__.py order_by_type=false wtforms-components-0.10.5/.travis.yml000066400000000000000000000013551400106477700176040ustar00rootroot00000000000000dist: xenial language: python python: - 2.7 - 3.4 - 3.5 - 3.6 - 3.7 - pypy - pypy3 env: matrix: - WTFORMS=WTForms==1.0.5 - WTFORMS=WTForms==2.0 - WTFORMS=WTForms==2.1 - WTFORMS=WTForms==2.2 - WTFORMS=WTForms==2.3 - WTFORMS=WTForms==3.0.0a1 jobs: exclude: - python: 2.7 env: WTFORMS=WTForms==3.0.0a1 - python: 3.4 env: WTFORMS=WTForms==3.0.0a1 - python: 3.5 env: WTFORMS=WTForms==3.0.0a1 - python: pypy env: WTFORMS=WTForms==3.0.0a1 install: - "pip install $WTFORMS" - pip install -e ".[test]" script: - isort --recursive --diff wtforms_components tests && isort --recursive --check-only wtforms_components tests - flake8 wtforms_components tests - py.test wtforms-components-0.10.5/CHANGES.rst000066400000000000000000000126131400106477700172740ustar00rootroot00000000000000Changelog --------- Here you can see the full list of changes between each WTForms-Components release. 0.10.5 (2021-01-17) ^^^^^^^^^^^^^^^^^^^ - Added WTForms 3.0 support (#71, pull request courtesy of jpic) 0.10.4 (2019-04-01) ^^^^^^^^^^^^^^^^^^^ - Added JSONField (#65, pull request courtesy fedExpress) 0.10.3 (2017-03-03) ^^^^^^^^^^^^^^^^^^^ - Made SelectWidget backwards compatible (#52, pull request courtesy tvuotila) 0.10.2 (2016-12-05) ^^^^^^^^^^^^^^^^^^^ - Made read_only also add disabled attribute (#51, pull request courtesy quantus) 0.10.1 (2016-11-22) ^^^^^^^^^^^^^^^^^^^ - Added seconds support for TimeField (#48, pull request courtesy tvuotila) 0.10.0 (2016-01-28) ^^^^^^^^^^^^^^^^^^^ - Moved GroupedQuerySelectField to WTForms-Alchemy - Moved PhoneNumber to WTForms-Alchemy - Moved WeekdaysField to WTForms-Alchemy - Moved Unique validator to WTForms-Alchemy - Remove AJAXField dependency on SQLAlchemy-Utils - Added PyPy support - Fixed IntervalFields to work with intervals 0.6.0 - Updated intervals requirement to 0.6.0 0.9.9 (2016-01-10) ^^^^^^^^^^^^^^^^^^ - Added sane error handling with Unique validator when Form is missing `_obj` attribute (#34) 0.9.8 (2015-09-28) ^^^^^^^^^^^^^^^^^^ - Added isort and flake8 checks to ensure all code is PEP8 compliant - Fields marked read only are no longer processed and populated 0.9.7 (2014-12-22) ^^^^^^^^^^^^^^^^^^ - Added blank_value option for GroupedQuerySelectField - Add py34 to test matrix - Fixed midnight handling for TimeField 0.9.6 (2014-09-04) ^^^^^^^^^^^^^^^^^^ - Fixed Unique validator session checking (#19). 0.9.5 (2014-07-31) ^^^^^^^^^^^^^^^^^^ - Fixed base_form option in SplitDateTimeField getting lost if form is initialized more than once. 0.9.4 (2014-07-29) ^^^^^^^^^^^^^^^^^^ - Added base_form option to SplitDateTimeField 0.9.3 (2014-05-15) ^^^^^^^^^^^^^^^^^^ - Fixed InstrumentedAttribute support for Unique validator, issue #13 - Removed CountryField (now part of WTForms-Alchemy) 0.9.2 (2014-03-26) ^^^^^^^^^^^^^^^^^^ - Added WeekDaysField 0.9.1 (2014-01-27) ^^^^^^^^^^^^^^^^^^ - Added new unique validator 0.9.0 (2014-01-14) ^^^^^^^^^^^^^^^^^^ - Deprecated NumberRangeField - Added IntIntervalField, FloatIntervalField, DecimalIntervalField, DateIntervalField, DateTimeIntervalField - Updated SQLAlchemy-Utils dependency to version 0.23.0 0.8.3 (2014-01-05) ^^^^^^^^^^^^^^^^^^ - Updated SQLAlchemy-Utils dependency to version 0.22.1 0.8.2 (2013-12-12) ^^^^^^^^^^^^^^^^^^ - Add default validation message for Email validator 0.8.1 (2013-11-30) ^^^^^^^^^^^^^^^^^^ - Fix import error with new versions of `validators` package. - Added initial WTForms 2.0 support 0.8.0 (2013-10-11) ^^^^^^^^^^^^^^^^^^ - Added Python 3 support 0.7.1 (2013-09-07) ^^^^^^^^^^^^^^^^^^ - Added AjaxField 0.7.0 (2013-08-09) ^^^^^^^^^^^^^^^^^^ - Added GroupedQuerySelectField 0.6.6 (2013-07-31) ^^^^^^^^^^^^^^^^^^ - Added HTML5 compatible basic parameters (disabled, required, autofocus and readonly) for all widgets 0.6.5 (2013-07-30) ^^^^^^^^^^^^^^^^^^ - Added step rendering for NumberInput and RangeInput widgets 0.6.4 (2013-07-22) ^^^^^^^^^^^^^^^^^^ - Packages colour and phonenumbers are now lazy imported 0.6.3 (2013-05-24) ^^^^^^^^^^^^^^^^^^ - Added EmailField to main import - Added SearchField, IntegerSliderField, DecimalSliderField 0.6.2 (2013-05-24) ^^^^^^^^^^^^^^^^^^ - Added TimeInput, URLInput, ColorInput and TelInput - Added TimeRange validator 0.6.1 (2013-05-23) ^^^^^^^^^^^^^^^^^^ - Added required flag for NumberInput, DateInput, DateTimeInput and DateTimeLocalInput whenever associated field has a DataRequired validator. 0.6.0 (2013-05-23) ^^^^^^^^^^^^^^^^^^ - IntegerField and DecimalField which create HTML5 compatible min and max attributes based on attached NumberRange validators - DateField, DateTimeField and DateTimeLocalField classes which create HTML5 compatible min and max attributes based on attached NumberRange validators 0.5.5 (2013-05-07) ^^^^^^^^^^^^^^^^^^ - Made TimeField use HTML5 TimeInput - Made PhoneNumberField use HTML5 TelInput - Made ColorField use HTML5 ColorInput - Updated WTForms dependency to 1.0.4 0.5.4 (2013-04-29) ^^^^^^^^^^^^^^^^^^ - Added ColorField 0.5.3 (2013-04-26) ^^^^^^^^^^^^^^^^^^ - Added read_only field marker function 0.5.2 (2013-04-12) ^^^^^^^^^^^^^^^^^^ - Added tests for TimeField - Added TimeField to main module import 0.5.1 (2013-04-12) ^^^^^^^^^^^^^^^^^^ - Added PassiveHiddenField 0.5.0 (2013-04-04) ^^^^^^^^^^^^^^^^^^ - Added Email validator - Fixed empty string handling with NumberRange fields 0.4.6 (2013-03-29) ^^^^^^^^^^^^^^^^^^ - Fixed Unique validator when using Form constructor obj parameter - Updated docs 0.4.5 (2013-03-27) ^^^^^^^^^^^^^^^^^^ - Fixed PhoneNumberField field rendering when validation fails 0.4.4 (2013-03-26) ^^^^^^^^^^^^^^^^^^ - Fixed NumberRangeField field rendering when validation fails 0.4.3 (2013-03-26) ^^^^^^^^^^^^^^^^^^ - Fixed NumberRangeField widget rendering 0.4.2 (2013-03-26) ^^^^^^^^^^^^^^^^^^ - Removed NumberRangeInput 0.4.1 (2013-03-26) ^^^^^^^^^^^^^^^^^^ - Changed empty phone number to be passed as None 0.4.0 (2013-03-26) ^^^^^^^^^^^^^^^^^^ - Added NumberRangeField 0.3.0 (2013-03-26) ^^^^^^^^^^^^^^^^^^ - Changed to use SQLAlchemy-Utils PhoneNumber class 0.2.0 (2013-03-20) ^^^^^^^^^^^^^^^^^^ - Added PhoneNumberField 0.1.0 (2013-03-15) ^^^^^^^^^^^^^^^^^^ - Initial public release wtforms-components-0.10.5/LICENSE000066400000000000000000000026541400106477700165030ustar00rootroot00000000000000Copyright (c) 2012, Konsta Vesterinen, Janne Vanhala All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * The names of the contributors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. wtforms-components-0.10.5/MANIFEST.in000066400000000000000000000003011400106477700172170ustar00rootroot00000000000000include CHANGES.rst LICENSE README.rst recursive-include tests * recursive-exclude tests *.pyc recursive-include docs * recursive-exclude docs *.pyc prune docs/_build exclude docs/_themes/.git wtforms-components-0.10.5/README.rst000066400000000000000000000014261400106477700171610ustar00rootroot00000000000000WTForms-Components ================== |Build Status| |Version Status| |Downloads| Additional fields, validators and widgets for WTForms. Resources --------- - `Documentation `_ - `Issue Tracker `_ - `Code `_ .. |Build Status| image:: https://travis-ci.org/kvesteri/wtforms-components.png?branch=master :target: https://travis-ci.org/kvesteri/wtforms-components .. |Version Status| image:: https://img.shields.io/pypi/v/WTForms-Components.svg :target: https://crate.io/packages/WTForms-Components/ .. |Downloads| image:: https://img.shields.io/pypi/dm/WTForms-Components.svg :target: https://crate.io/packages/WTForms-Components/ wtforms-components-0.10.5/docs/000077500000000000000000000000001400106477700164175ustar00rootroot00000000000000wtforms-components-0.10.5/docs/Makefile000066400000000000000000000127541400106477700200700ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/WTForms-Components.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/WTForms-Components.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/WTForms-Components" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/WTForms-Components" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." wtforms-components-0.10.5/docs/conf.py000066400000000000000000000201131400106477700177130ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # WTForms-Components documentation build configuration file, created by # sphinx-quickstart on Fri Mar 15 10:35:33 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import os import sys # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.ifconfig', 'sphinx.ext.viewcode'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'WTForms-Components' copyright = u'2013, Konsta Vesterinen, Janne Vanhala, Vesa Uimonen' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.1' # The full version, including alpha/beta/rc tags. release = '0.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'WTForms-Componentsdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'WTForms-Components.tex', u'WTForms-Components Documentation', u'Konsta Vesterinen, Janne Vanhala, Vesa Uimonen', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'wtforms-components', u'WTForms-Components Documentation', [u'Konsta Vesterinen, Janne Vanhala, Vesa Uimonen'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'WTForms-Components', u'WTForms-Components Documentation', u'Konsta Vesterinen, Janne Vanhala, Vesa Uimonen', 'WTForms-Components', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'http://docs.python.org/': None} wtforms-components-0.10.5/docs/index.rst000066400000000000000000000150721400106477700202650ustar00rootroot00000000000000WTForms-Components ================== WTForms-Components provides various additional fields, validators and widgets for WTForms. Fields ====== WTForms derived HTML5 Fields ----------------------------- WTForms-Components provides enhanced versions of WTForms HTML5 fields. These fields support HTML5 compatible min and max validators. WTForms-Components is smart enough to automatically attach HTML5 min and max validators based on field's NumberRange and DateRange validators. Example: :: from wtforms import Form from wtforms_components import DateTimeField from werkzeug.datastructures import MultiDict class TestForm(Form): test_field = DateTimeField( 'Date', validators=[DateRange( min=datetime(2000, 1, 1), max=datetime(2000, 10, 10) )] ) form = TestForm(MultiDict(test_field='2000-2-2')) form.test_field # ' Same applies to IntegerField: :: from wtforms import Form from wtforms_components import IntegerField from werkzeug.datastructures import MultiDict class TestForm(Form): test_field = IntegerField( 'Date', validators=[NumberRange( min=1, max=4 )] ) form = TestForm(MultiDict(test_field='3')) form.test_field # ' SelectField & SelectMultipleField ----------- WTForms-Components provides enhanced versions of WTForms SelectFields. Both WTForms-Components SelectField and SelectMultipleField support the following enhancements: - Ability to generate `optgroup`_ elements. - ``choices`` can be a callable, which allows for dynamic choices. With the plain version of WTForms this has to be added manually, after instantiation of the form. .. _`optgroup`: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/optgroup PhoneNumberField ---------------- Older versions of WTForms-Components had a PhoneNumberField. As of version 0.10.0 this field has now been moved to `WTForms-Alchemy`_. .. _WTForms-Alchemy: https://github.com/kvesteri/wtforms-alchemy ColorField ---------- ColorField is a string field representing a Color object from `colour`_ package. .. _colour: https://github.com/vaab/colour Example: :: from wtforms import Form from wtforms_components import ColorField class DocumentForm(Form): background_color = ColorField() NumberRangeField ---------------- NumberRangeField is a string field representing a NumberRange object from `SQLAlchemy-Utils`_. .. _SQLAlchemy-Utils: https://github.com/kvesteri/sqlalchemy-utils Example: :: from wtforms import Form from wtforms_components import NumberRangeField class EventForm(Form): estimated_participants = NumberRangeField('Estimated participants') PassiveHiddenField ------------------ PassiveHiddenField acts just like normal wtforms.fields.HiddenField except it doesn't populate object values with populate_obj function. Example: :: from wtforms import Form, TextField from wtforms_components import PassiveHiddenField class EventForm(Form): id = PassiveHiddenField() name = TextField('Name') TimeField --------- TimeField is a string field which stores a `datetime.time` matching a format. :: from wtforms import Form, DateField from wtforms_components import TimeField class EventForm(Form): start_date = DateField('Start date') start_time = TimeField('Start time') Read-only fields ---------------- WTForms-Components provides a convenient function for making fields read-only. In the following example we define a form where name field is defined as read-only. :: from wtforms import Form, DateField, TextField from wtforms_components import TimeField, read_only class EventForm(Form): name = TextField('Name') start_date = DateField('Start date') start_time = TimeField('Start time') def __init__(self, *args, **kwargs): super(EventForm, self).__init__(*args, **kwargs) read_only(self.name) Validators ========== DateRange validator ------------------- The DateRange validator is essentially the same as wtforms.validators.NumberRange validator but validates dates. In the following example we define a start_time and a start_date field, which do not accept dates in the past. :: from datetime import datetime, date from wtforms import Form from wtforms.fields import DateField from wtforms_components import DateRange class EventForm(Form): start_time = DateField( validators=[DateRange(min=datetime.now())] ) start_date = DateField( validators=[DateRange(min=date.today())] ) Email validator --------------- Validates an email address. This validator is based on `Django's email validator`_ and is stricter than the standard email validator included in WTForms. Example: :: from wtforms import Form from wtforms.fields import TextField from wtforms_components import Email class UserForm(Form): email = TextField( validators=[Email()] ) If validator ------------ The If validator provides means for having conditional validations. In the following example we only validate field email if field user_id is provided. :: from wtforms import Form from wtforms.fields import IntegerField, TextField from wtforms_components import If class SomeForm(Form): user_id = IntegerField() email = TextField(validators=[ If(lambda form, field: form.user_id.data, Email()) ]) Chain validator --------------- Chain validator chains validators together. Chain validator can be combined with If validator to provide nested conditional validations. :: from wtforms import Form from wtforms.fields import IntegerField, TextField from wtforms_components import If class SomeForm(Form): user_id = IntegerField() email = TextField(validators=[ If( lambda form, field: form.user_id.data, Chain(DataRequired(), Email()) ) ]) Unique Validator ---------------- Unique validator provides convenient way for checking the unicity of given field in database. As of WTForms-Components version 0.10.0 the Unique validator has been moved to WTForms-Alchemy due to its SQLAlchemy dependency. wtforms-components-0.10.5/docs/make.bat000066400000000000000000000120001400106477700200150ustar00rootroot00000000000000@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . set I18NSPHINXOPTS=%SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over all changed/added/deprecated items echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\WTForms-Components.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\WTForms-Components.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) :end wtforms-components-0.10.5/setup.cfg000066400000000000000000000000771400106477700173140ustar00rootroot00000000000000[bdist_wheel] universal = 1 [metadata] license_file = LICENSE wtforms-components-0.10.5/setup.py000066400000000000000000000050201400106477700171760ustar00rootroot00000000000000""" WTForms-Components ------------------ Additional fields, validators and widgets for WTForms. """ import os import re import sys from setuptools import setup HERE = os.path.dirname(os.path.abspath(__file__)) PY3 = sys.version_info[0] == 3 def get_version(): filename = os.path.join(HERE, 'wtforms_components', '__init__.py') with open(filename) as f: contents = f.read() pattern = r"^__version__ = '(.*?)'$" return re.search(pattern, contents, re.MULTILINE).group(1) extras_require = { 'test': [ 'pytest>=2.2.3', 'flexmock>=0.9.7', 'WTForms-Test>=0.1.1', 'flake8==3.8.4', 'isort==4.3.21', ], 'color': ['colour>=0.0.4'], 'ipaddress': ['ipaddr'] if not PY3 else [], 'timezone': ['python-dateutil'], } # Add all optional dependencies to testing requirements. for name, requirements in extras_require.items(): if name != 'test': extras_require['test'] += requirements setup( name='WTForms-Components', version=get_version(), url='https://github.com/kvesteri/wtforms-components', license='BSD', author='Konsta Vesterinen', author_email='konsta@fastmonkeys.com', description='Additional fields, validators and widgets for WTForms.', long_description=__doc__, packages=[ 'wtforms_components', 'wtforms_components.fields' ], zip_safe=False, include_package_data=True, platforms='any', install_requires=[ 'WTForms>=1.0.4', 'six>=1.4.1', 'email_validator>=1.0.0', 'validators>=0.5.0' if PY3 else 'validators<=0.15', 'intervals>=0.6.0', 'MarkupSafe>=1.0.0' ], extras_require=extras_require, classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ] ) wtforms-components-0.10.5/tests/000077500000000000000000000000001400106477700166315ustar00rootroot00000000000000wtforms-components-0.10.5/tests/__init__.py000066400000000000000000000034421400106477700207450ustar00rootroot00000000000000from wtforms import Form from wtforms.validators import DataRequired from wtforms_test import FormTestCase class MultiDict(dict): def getlist(self, key): return [self[key]] class SimpleFieldTestCase(FormTestCase): field_class = None def init_form(self, **kwargs): class TestForm(Form): test_field = self.field_class(**kwargs) self.form_class = TestForm return self.form_class class FieldTestCase(SimpleFieldTestCase): def test_assigns_required_from_validator(self): form_class = self.init_form( validators=[DataRequired()] ) form = form_class() assert ( '' ) wtforms-components-0.10.5/tests/fields/test_date_time_field.py000066400000000000000000000013071400106477700246070ustar00rootroot00000000000000from datetime import datetime from tests import FieldTestCase, MultiDict from wtforms_components import DateRange, DateTimeField class TestDateTimeField(FieldTestCase): field_class = DateTimeField def test_assigns_min_and_max(self): form_class = self.init_form( validators=[DateRange( min=datetime(2000, 1, 1), max=datetime(2000, 10, 10) )] ) form = form_class(MultiDict(test_field='2000-2-2')) assert str(form.test_field) == ( '' ) wtforms-components-0.10.5/tests/fields/test_date_time_local_field.py000066400000000000000000000013321400106477700257570ustar00rootroot00000000000000from datetime import datetime from tests import FieldTestCase, MultiDict from wtforms_components import DateRange, DateTimeLocalField class TestDateTimeLocalField(FieldTestCase): field_class = DateTimeLocalField def test_assigns_min_and_max(self): form_class = self.init_form( validators=[DateRange( min=datetime(2000, 1, 1), max=datetime(2000, 10, 10) )] ) form = form_class(MultiDict(test_field='2000-2-2')) assert str(form.test_field) == ( '' ) wtforms-components-0.10.5/tests/fields/test_decimal_field.py000066400000000000000000000016671400106477700242630ustar00rootroot00000000000000from wtforms.validators import NumberRange from tests import FieldTestCase, MultiDict from wtforms_components import DecimalField from wtforms_components.widgets import NumberInput class TestDecimalField(FieldTestCase): field_class = DecimalField def test_assigns_min_and_max(self): form_class = self.init_form( validators=[NumberRange(min=2, max=10)] ) form = form_class(MultiDict(test_field=3)) assert str(form.test_field) == ( '' ) def test_assigns_step(self): form_class = self.init_form( widget=NumberInput(step='0.1') ) form = form_class(MultiDict(test_field=3)) assert str(form.test_field) == ( '' ) wtforms-components-0.10.5/tests/fields/test_int_interval_field.py000066400000000000000000000037251400106477700253600ustar00rootroot00000000000000from wtforms import Form from wtforms_test import FormTestCase from tests import MultiDict from wtforms_components import FloatIntervalField, IntIntervalField class RangeFieldTestCase(FormTestCase): def init_form(self, **kwargs): class TestForm(Form): interval = self.interval_field(**kwargs) self.form_class = TestForm return self.form_class def test_valid_intervals(self): form_class = self.init_form() for interval in self.valid_ranges: form = form_class(MultiDict(interval=interval)) form.validate() assert len(form.errors) == 0 def test_invalid_intervals(self): form_class = self.init_form() for interval in self.invalid_ranges: form = form_class(MultiDict(interval=interval)) form.validate() assert len(form.errors['interval']) == 1 def test_field_rendering_when_validation_fails(self): form_class = self.init_form() form = form_class(MultiDict(interval='invalid')) form.validate() assert 'value="invalid"' in str(form.interval) def test_converts_empty_strings_to_none(self): form_class = self.init_form() form = form_class(MultiDict(interval='')) assert form.data == {'interval': None} class TestIntIntervalField(RangeFieldTestCase): def setup_method(self, method): self.valid_ranges = [ '13 - 14', '13 - 13', '0 - 99', '88' ] self.invalid_ranges = [ 'abc', '14 - 13', ] self.interval_field = IntIntervalField class TestFloatIntervalField(RangeFieldTestCase): def setup_method(self, method): self.valid_ranges = [ '13 - 14', '13 - 13', '0 - 99', '88' ] self.invalid_ranges = [ 'abc', '14 - 13', ] self.interval_field = FloatIntervalField wtforms-components-0.10.5/tests/fields/test_integer_field.py000066400000000000000000000010401400106477700243030ustar00rootroot00000000000000from wtforms.validators import NumberRange from tests import FieldTestCase, MultiDict from wtforms_components import IntegerField class TestIntegerField(FieldTestCase): field_class = IntegerField def test_assigns_min_and_max(self): form_class = self.init_form(validators=[NumberRange(min=2, max=10)]) form = form_class(MultiDict(test_field=3)) assert str(form.test_field) == ( '' ) wtforms-components-0.10.5/tests/fields/test_json_field.py000066400000000000000000000016361400106477700236320ustar00rootroot00000000000000from tests import MultiDict, SimpleFieldTestCase from wtforms_components import JSONField class TestJSONField(SimpleFieldTestCase): field_class = JSONField def setup_method(self, method): self.valid_jsons = [ '{"a": {"b": true, "c": "lv", "d": 3}, "e": {"f": {"g": [85]}}}' ] self.invalid_jsons = [ '{"a": {"b": bzz, "c": "lv", "d": 3}, "e": {"f": {"g": [85]}}}' ] def test_valid_times(self): form_class = self.init_form() for time_ in self.valid_jsons: form = form_class(MultiDict(test_field=time_)) form.validate() assert len(form.errors) == 0 def test_invalid_times(self): form_class = self.init_form() for time_ in self.invalid_jsons: form = form_class(MultiDict(test_field=time_)) form.validate() assert len(form.errors['test_field']) == 1 wtforms-components-0.10.5/tests/fields/test_passive_hidden_field.py000066400000000000000000000007261400106477700256450ustar00rootroot00000000000000from wtforms import Form from wtforms_test import FormTestCase from tests import MultiDict from wtforms_components import PassiveHiddenField class TestPassiveHiddenField(FormTestCase): def test_does_not_populate_obj_values(self): class MyForm(Form): id = PassiveHiddenField() class A(object): id = None form = MyForm(MultiDict({'id': 12})) a = A() form.populate_obj(a) assert a.id is None wtforms-components-0.10.5/tests/fields/test_read_only_fields.py000066400000000000000000000011101400106477700250030ustar00rootroot00000000000000from wtforms.fields import BooleanField from tests import MultiDict, SimpleFieldTestCase from wtforms_components import read_only class TestReadOnlyCheckboxField(SimpleFieldTestCase): field_class = BooleanField def test_has_readonly_and_disabled_attributes_in_html(self): form_class = self.init_form() form = form_class(MultiDict(test_field='y')) read_only(form.test_field) assert ( '' ) in str(form.test_field) wtforms-components-0.10.5/tests/fields/test_search_field.py000066400000000000000000000002211400106477700241130ustar00rootroot00000000000000from tests import FieldTestCase from wtforms_components import SearchField class TestSearchField(FieldTestCase): field_class = SearchField wtforms-components-0.10.5/tests/fields/test_select_field.py000066400000000000000000000067511400106477700241430ustar00rootroot00000000000000from wtforms import Form from wtforms_test import FormTestCase from tests import MultiDict from wtforms_components import SelectField class Dummy(object): fruits = [] class TestSelectField(FormTestCase): choices = ( ('Fruits', ( ('apple', 'Apple'), ('peach', 'Peach'), ('pear', 'Pear') )), ('Vegetables', ( ('cucumber', 'Cucumber'), ('potato', 'Potato'), ('tomato', 'Tomato'), )) ) def init_form(self, **kwargs): class TestForm(Form): fruit = SelectField(**kwargs) self.form_class = TestForm return self.form_class def test_understands_nested_choices(self): form_class = self.init_form(choices=self.choices) form = form_class( MultiDict([('fruit', 'invalid')]) ) form.validate() assert len(form.errors['fruit']) == 1 def test_understands_mixing_of_choice_types(self): choices = ( ('Fruits', ( ('apple', 'Apple'), ('peach', 'Peach'), ('pear', 'Pear') )), ('cucumber', 'Cucumber'), ) form_class = self.init_form(choices=choices) form = form_class(MultiDict([('fruit', 'cucumber')])) form.validate() assert len(form.errors) == 0 def test_understands_callables_as_choices(self): form_class = self.init_form(choices=lambda: []) form = form_class( MultiDict([('fruit', 'invalid')]) ) form.validate() assert len(form.errors['fruit']) == 1 def test_option_selected(self): form_class = self.init_form(choices=self.choices) obj = Dummy() obj.fruit = 'peach' form = form_class( obj=obj ) assert ( '' in str(form.fruit) ) def test_nested_option_selected_by_field_default_value(self): form_class = self.init_form( choices=self.choices, default='pear' ) form = form_class() assert ( '' in str(form.fruit) ) def test_option_selected_by_field_default_value(self): choices = [ ('apple', 'Apple'), ('peach', 'Peach'), ('pear', 'Pear') ] form_class = self.init_form( choices=choices, default='pear' ) form = form_class() assert ( '' in str(form.fruit) ) def test_callable_option_selected_by_field_default_value(self): def choices(): return [ ('apple', 'Apple'), ('peach', 'Peach'), ('pear', 'Pear') ] form_class = self.init_form( choices=choices, default='pear' ) form = form_class() assert ( '' in str(form.fruit) ) def test_data_coercion(self): choices = ( ('Fruits', ( (0, 'Apple'), (1, 'Peach'), (2, 'Pear') )), (3, 'Cucumber'), ) form_class = self.init_form(choices=choices, coerce=int) form = form_class(MultiDict([('fruit', '1')])) form.validate() assert not form.errors wtforms-components-0.10.5/tests/fields/test_select_multiple_field.py000066400000000000000000000026221400106477700260470ustar00rootroot00000000000000from wtforms import Form from wtforms_test import FormTestCase from tests import MultiDict from wtforms_components import SelectMultipleField class Dummy(object): fruits = [] class TestSelectMultipleField(FormTestCase): choices = ( ('Fruits', ( ('apple', 'Apple'), ('peach', 'Peach'), ('pear', 'Pear') )), ('Vegetables', ( ('cucumber', 'Cucumber'), ('potato', 'Potato'), ('tomato', 'Tomato'), )) ) def init_form(self, **kwargs): class TestForm(Form): fruits = SelectMultipleField(**kwargs) self.form_class = TestForm return self.form_class def test_understands_nested_choices(self): form_class = self.init_form(choices=self.choices) form = form_class( MultiDict([ ('fruits', 'apple'), ('fruits', 'invalid') ]) ) form.validate() assert form.errors == { 'fruits': [u"'invalid' is not a valid choice for this field"] } def test_option_selected(self): form_class = self.init_form(choices=self.choices) obj = Dummy() obj.fruits = ['peach'] form = form_class( obj=obj ) assert ( '' in str(form.fruits) ) wtforms-components-0.10.5/tests/fields/test_split_date_time_field.py000066400000000000000000000066201400106477700260250ustar00rootroot00000000000000from datetime import date, datetime, time from wtforms import Form from wtforms.validators import DataRequired from tests import MultiDict, SimpleFieldTestCase from wtforms_components.fields import SplitDateTimeField class Obj(object): test_field = None class TestSplitDateTimeField(SimpleFieldTestCase): field_class = SplitDateTimeField def test_assigns_required_to_date(self): form_class = self.init_form(datetime_form={ 'date': {'validators': [DataRequired()]} }) form = form_class() assert str(form.test_field.date) == ( '' ) def test_renders_date_field(self): form_class = self.init_form() form = form_class() assert str(form.test_field.date) == ( '' ) def test_assigns_required_to_time(self): form_class = self.init_form(datetime_form={ 'time': {'validators': [DataRequired()]} }) form = form_class() assert str(form.test_field.time) == ( '' ) def test_renders_time_field(self): form_class = self.init_form() form = form_class() assert str(form.test_field.time) == ( '' ) def test_processes_values(self): form_class = self.init_form() form = form_class(MultiDict({ 'test_field-date': '2000-3-2', 'test_field-time': '19:10', })) assert form.test_field.data['date'] == date(2000, 3, 2) assert form.test_field.data['time'] == time(19, 10) def test_populates_object(self): form_class = self.init_form() form = form_class(MultiDict({ 'test_field-date': '2000-3-2', 'test_field-time': '19:10', })) obj = Obj() form.populate_obj(obj) assert obj.test_field == datetime(2000, 3, 2, 19, 10) def test_processes_values_when_format_is_set(self): form_class = self.init_form(datetime_form={ 'date': {'format': '%d.%m.%Y'}, 'time': {'format': '%H.%M'}, }) form = form_class(MultiDict({ 'test_field-date': '2.3.2000', 'test_field-time': '19.10', })) assert form.test_field.data['date'] == date(2000, 3, 2) assert form.test_field.data['time'] == time(19, 10) def test_default_base_form(self): form_class = self.init_form() form = form_class() assert form.test_field.form.__class__.__bases__ == (Form,) def test_custom_base_form(self): class A(Form): pass form_class = self.init_form(datetime_form={'base_form': A}) form = form_class() assert form.test_field.form.__class__.__bases__ == (A,) def test_custom_base_form_with_two_instances(self): class A(Form): pass form_class = self.init_form(datetime_form={'base_form': A}) form = form_class() form2 = form_class() assert form.test_field.form.__class__.__bases__ == (A,) assert form2.test_field.form.__class__.__bases__ == (A,) wtforms-components-0.10.5/tests/fields/test_string_field.py000066400000000000000000000002211400106477700241540ustar00rootroot00000000000000from tests import FieldTestCase from wtforms_components import StringField class TestStringField(FieldTestCase): field_class = StringField wtforms-components-0.10.5/tests/fields/test_time_field.py000066400000000000000000000041001400106477700236040ustar00rootroot00000000000000from datetime import time from tests import FieldTestCase, MultiDict from wtforms_components import TimeField, TimeRange class TestTimeField(FieldTestCase): field_class = TimeField def setup_method(self, method): self.valid_times = [ '00:00', '11:11', '12:15' ] self.invalid_times = [ '00:61', '25:01', 'unknown', ] def test_valid_times(self): form_class = self.init_form() for time_ in self.valid_times: form = form_class(MultiDict(test_field=time_)) form.validate() assert len(form.errors) == 0 def test_invalid_times(self): form_class = self.init_form() for time_ in self.invalid_times: form = form_class(MultiDict(test_field=time_)) form.validate() assert len(form.errors['test_field']) == 1 def test_assigns_min_and_max(self): form_class = self.init_form( validators=[TimeRange( min=time(12, 12), max=time(13, 30) )] ) form = form_class(MultiDict(test_field='13:20')) assert str(form.test_field) == ( '' ) def test_renders_input_time_at_midnight(self): form_class = self.init_form() form = form_class(MultiDict(test_field='00:00')) assert str(form.test_field) == ( '' ) class TestTimeFieldWithSeconds(TestTimeField): def setup_method(self, method): self.valid_times = [ '00:00:00', '11:11:11', '12:15:17' ] self.invalid_times = [ '00:61', '01:01:61', 'unknown', ] def init_form(self, **kwargs): kwargs['format'] = '%H:%M:%S' return super(TestTimeFieldWithSeconds, self).init_form(**kwargs) wtforms-components-0.10.5/tests/test_chain_validator.py000066400000000000000000000011461400106477700233730ustar00rootroot00000000000000from wtforms import Form from wtforms.validators import DataRequired, Email from wtforms_test import FormTestCase from tests import MultiDict from wtforms_components import Chain try: from wtforms.fields import TextField except ImportError: # wtforms3 from wtforms.fields import StringField as TextField class TestChainValidator(FormTestCase): def test_validates_whole_chain(self): class MyForm(Form): email = TextField(validators=[Chain([DataRequired(), Email()])]) form = MyForm(MultiDict({'name': ''})) form.validate() assert 'email' in form.errors wtforms-components-0.10.5/tests/test_date_range_validator.py000066400000000000000000000025151400106477700244030ustar00rootroot00000000000000from datetime import date from wtforms import Form from wtforms.fields import DateField from wtforms_test import FormTestCase from tests import MultiDict from wtforms_components import DateRange class TestDateRangeValidator(FormTestCase): def init_form(self, **kwargs): class ModelTestForm(Form): date = DateField(validators=[DateRange(**kwargs)]) self.form_class = ModelTestForm return self.form_class def test_date_greater_than_validator(self): form_class = self.init_form(min=date(1990, 1, 1)) form = form_class(MultiDict(date='1980-1-1')) form.validate() error_msg = u'Date must be greater than 1990-01-01.' assert form.errors['date'] == [error_msg] def test_date_less_than_validator(self): form_class = self.init_form(max=date(1990, 1, 1)) form = form_class(MultiDict(date='1991-1-1')) form.validate() error_msg = u'Date must be less than 1990-01-01.' assert form.errors['date'] == [error_msg] def test_date_between_validator(self): form_class = self.init_form(min=date(1990, 1, 1), max=date(1991, 1, 1)) form = form_class(MultiDict(date='1989-1-1')) form.validate() error_msg = u'Date must be between 1990-01-01 and 1991-01-01.' assert form.errors['date'] == [error_msg] wtforms-components-0.10.5/tests/test_email_validator.py000066400000000000000000000050061400106477700233770ustar00rootroot00000000000000# -*- coding: utf-8 -*- import pytest from wtforms.validators import ValidationError from wtforms_components import Email class DummyTranslations(object): def gettext(self, string): return string def ngettext(self, singular, plural, n): if n == 1: return singular return plural class DummyForm(dict): pass class DummyField(object): _translations = DummyTranslations() def __init__(self, data, errors=(), raw_data=None): self.data = data self.errors = list(errors) self.raw_data = raw_data def gettext(self, string): return self._translations.gettext(string) def ngettext(self, singular, plural, n): return self._translations.ngettext(singular, plural, n) class TestEmailValidator(object): def setup_method(self, method): self.form = DummyForm() @pytest.mark.parametrize(("email", "whitelist"), [ ('email@here.com', None), ('weirder-email@here.and.there.com', None), ('email@[127.0.0.1]', None), ('example@valid-----hyphens.com', None), ('example@valid-with-hyphens.com', None), ('test@domain.with.idn.tld.उदाहरण.परीक्षा', None), ('email@localhost', None), ('email@localdomain', ['localdomain']), ('"test@test"@example.com', None), ('"\\\011"@here.com', None), ]) def test_returns_none_on_valid_email(self, email, whitelist): validate_email = Email(whitelist=whitelist) validate_email(self.form, DummyField(email)) @pytest.mark.parametrize(("email",), [ (None,), ('',), ('abc',), ('abc@',), ('abc@bar',), ('a @x.cz',), ('abc@.com',), ('something@@somewhere.com',), ('email@127.0.0.1',), ('example@invalid-.com',), ('example@-invalid.com',), ('example@inv-.alid-.com',), ('example@inv-.-alid.com',), # Quoted-string format (CR not allowed) ('"\\\012"@here.com',), ]) def test_raises_validationerror_on_invalid_email(self, email): validate_email = Email() with pytest.raises(ValidationError): validate_email(self.form, DummyField(email)) def test_default_validation_error_message(self): validate_email = Email() try: validate_email(self.form, DummyField('@@@')) assert False, 'No validation error thrown.' except ValidationError as e: assert str(e) == 'Invalid email address.' wtforms-components-0.10.5/tests/test_if_validator.py000066400000000000000000000027551400106477700227160ustar00rootroot00000000000000from wtforms import Form from wtforms.validators import DataRequired from wtforms_test import FormTestCase from tests import MultiDict from wtforms_components import If try: from wtforms.fields import TextField except ImportError: # wtforms3 from wtforms.fields import StringField as TextField class TestIfValidator(FormTestCase): def test_only_validates_if_condition_returns_true(self): class MyForm(Form): name = TextField(validators=[ If( lambda form, field: False, DataRequired(), ) ]) form = MyForm(MultiDict({'name': ''})) form.validate() assert not form.errors def test_encapsulates_given_validator(self): class MyForm(Form): name = TextField(validators=[ If( lambda form, field: True, DataRequired(), ) ]) form = MyForm(MultiDict({'name': ''})) form.validate() assert 'name' in form.errors def test_supports_custom_error_messages(self): class MyForm(Form): name = TextField(validators=[ If( lambda form, field: True, DataRequired(), message='Validation failed.' ) ]) form = MyForm(MultiDict({'name': ''})) form.validate() assert form.errors['name'] == ['Validation failed.'] wtforms-components-0.10.5/tests/test_read_only_function.py000066400000000000000000000023141400106477700241230ustar00rootroot00000000000000from wtforms import Form from wtforms_test import FormTestCase from tests import MultiDict from wtforms_components import read_only try: from wtforms.fields import TextField except ImportError: # wtforms3 from wtforms.fields import StringField as TextField class TestReadOnlyFunction(FormTestCase): def test_prevents_value_changing(self): class MyForm(Form): name = TextField(default='') form = MyForm() read_only(form.name) form.process(MultiDict({'name': 'New value'})) assert form.name.data == '' def test_preserves_previous_value(self): class MyForm(Form): name = TextField() form = MyForm() form.name.data = 'Previous value' read_only(form.name) form.process(MultiDict({'name': 'New value'})) assert form.name.data == 'Previous value' def test_prevents_value_population(self): class MyForm(Form): name = TextField() class MyModel(object): pass form = MyForm() model = MyModel() form.name.data = 'Existing value' read_only(form.name) form.populate_obj(model) assert not hasattr(model, 'name') wtforms-components-0.10.5/tests/test_time_range_validator.py000066400000000000000000000023721400106477700244250ustar00rootroot00000000000000from datetime import time from wtforms import Form from wtforms_test import FormTestCase from tests import MultiDict from wtforms_components import TimeField, TimeRange class TestTimeRangeValidator(FormTestCase): def init_form(self, **kwargs): class ModelTestForm(Form): time = TimeField(validators=[TimeRange(**kwargs)]) self.form_class = ModelTestForm return self.form_class def test_time_greater_than_validator(self): form_class = self.init_form(min=time(12)) form = form_class(MultiDict(time='11:12')) form.validate() error_msg = u'Time must be greater than 12:00.' assert form.errors['time'] == [error_msg] def test_time_less_than_validator(self): form_class = self.init_form(max=time(13, 30)) form = form_class(MultiDict(time='13:40')) form.validate() error_msg = u'Time must be less than 13:30.' assert form.errors['time'] == [error_msg] def test_time_between_validator(self): form_class = self.init_form(min=time(12), max=time(13)) form = form_class(MultiDict(time='14:30')) form.validate() error_msg = u'Time must be between 12:00 and 13:00.' assert form.errors['time'] == [error_msg] wtforms-components-0.10.5/tests/test_widgets.py000066400000000000000000000022761400106477700217170ustar00rootroot00000000000000from wtforms import Form from wtforms.fields import SelectField from wtforms_test import FormTestCase from wtforms_components import SelectWidget class Dummy(object): fruits = None class TestSelectWidgetWithNativeSelect(FormTestCase): choices = ( ('apple', 'Apple'), ('peach', 'Peach'), ('pear', 'Pear'), ('cucumber', 'Cucumber'), ('potato', 'Potato'), ('tomato', 'Tomato'), ) def init_form(self, **kwargs): class TestForm(Form): fruit = SelectField(widget=SelectWidget(), **kwargs) self.form_class = TestForm return self.form_class def test_option_selected(self): form_class = self.init_form(choices=self.choices) obj = Dummy() obj.fruit = 'peach' form = form_class( obj=obj ) assert ( '' in str(form.fruit) ) def test_default_value(self): form_class = self.init_form(choices=self.choices, default='pear') form = form_class() assert ( '' in str(form.fruit) ) wtforms-components-0.10.5/tox.ini000066400000000000000000000022541400106477700170050ustar00rootroot00000000000000# Tox (http://tox.testrun.org/) is a tool for running tests # in multiple virtualenvs. This configuration file will run the # test suite on all supported python versions. To use it, "pip install tox" # and then run "tox" from this directory. [tox] envlist = py26, py27, py37, py26-wtforms2, py27-wtforms2, py34-wtforms2, py35-wtforms2, py36-wtforms2, py37-wtforms2 [testenv] commands = pip install -e ".[test]" py.test install_command = pip install {packages} deps = WTForms==1.0.5 [testenv:py26-wtforms2] basepython = python2.6 deps = https://github.com/wtforms/wtforms/archive/wtforms2.zip [testenv:py27-wtforms2] basepython = python2.7 deps = https://github.com/wtforms/wtforms/archive/wtforms2.zip [testenv:py34-wtforms2] basepython = python3.4 deps = https://github.com/wtforms/wtforms/archive/wtforms2.zip [testenv:py35-wtforms2] basepython = python3.5 deps = https://github.com/wtforms/wtforms/archive/wtforms2.zip [testenv:py36-wtforms2] basepython = python3.6 deps = https://github.com/wtforms/wtforms/archive/wtforms2.zip [testenv:py37-wtforms2] basepython = python3.7 deps = https://github.com/wtforms/wtforms/archive/wtforms2.zip wtforms-components-0.10.5/wtforms_components/000077500000000000000000000000001400106477700214355ustar00rootroot00000000000000wtforms-components-0.10.5/wtforms_components/__init__.py000066400000000000000000000033071400106477700235510ustar00rootroot00000000000000from wtforms import Form from .fields import ( ColorField, DateField, DateIntervalField, DateTimeField, DateTimeIntervalField, DateTimeLocalField, DecimalField, DecimalIntervalField, DecimalSliderField, EmailField, FloatIntervalField, IntegerField, IntegerSliderField, IntIntervalField, JSONField, PassiveHiddenField, SearchField, SelectField, SelectMultipleField, SplitDateTimeField, StringField, TimeField ) from .validators import Chain, DateRange, Email, If, TimeRange from .widgets import NumberInput, ReadOnlyWidgetProxy, SelectWidget __version__ = '0.10.5' __all__ = ( Chain, ColorField, DateField, DateIntervalField, DateRange, DateTimeField, DateTimeIntervalField, DateTimeLocalField, DecimalField, DecimalIntervalField, DecimalSliderField, Email, EmailField, FloatIntervalField, If, IntegerField, IntegerSliderField, IntIntervalField, JSONField, NumberInput, PassiveHiddenField, SearchField, SelectField, SelectMultipleField, SelectWidget, SplitDateTimeField, StringField, TimeField, TimeRange ) class ModelForm(Form): """ Simple ModelForm, use this if your form needs to use the Unique validator """ def __init__(self, formdata=None, obj=None, prefix='', **kwargs): Form.__init__( self, formdata=formdata, obj=obj, prefix=prefix, **kwargs ) self._obj = obj def do_nothing(*args, **kwargs): pass def read_only(field): field.widget = ReadOnlyWidgetProxy(field.widget) field.process = do_nothing field.populate_obj = do_nothing return field wtforms-components-0.10.5/wtforms_components/_compat.py000066400000000000000000000003601400106477700234300ustar00rootroot00000000000000import functools import markupsafe try: from html import escape as html_escape except ImportError: from cgi import escape as _cgi_escape html_escape = functools.partial(_cgi_escape, quote=True) HTMLString = markupsafe.Markup wtforms-components-0.10.5/wtforms_components/fields/000077500000000000000000000000001400106477700227035ustar00rootroot00000000000000wtforms-components-0.10.5/wtforms_components/fields/__init__.py000066400000000000000000000021601400106477700250130ustar00rootroot00000000000000from .ajax import AjaxField from .color import ColorField from .html5 import ( DateField, DateTimeField, DateTimeLocalField, DecimalField, DecimalSliderField, EmailField, IntegerField, IntegerSliderField, SearchField, StringField ) from .interval import ( DateIntervalField, DateTimeIntervalField, DecimalIntervalField, FloatIntervalField, IntIntervalField ) from .json_field import JSONField from .passive_hidden import PassiveHiddenField from .select import SelectField from .select_multiple import SelectMultipleField from .split_date_time import SplitDateTimeField from .time import TimeField __all__ = ( AjaxField, ColorField, DateField, DateIntervalField, DateTimeField, DateTimeIntervalField, DateTimeLocalField, DecimalField, DecimalIntervalField, DecimalSliderField, EmailField, FloatIntervalField, IntegerField, IntegerSliderField, IntIntervalField, JSONField, PassiveHiddenField, SearchField, SelectField, SelectMultipleField, SplitDateTimeField, StringField, TimeField ) wtforms-components-0.10.5/wtforms_components/fields/ajax.py000066400000000000000000000052311400106477700242010ustar00rootroot00000000000000# -*- coding: utf-8 -*- import operator import six from wtforms import fields, widgets from wtforms.validators import ValidationError anyjson = None try: import anyjson except ImportError: pass class ImproperlyConfigured(Exception): pass class AjaxField(fields.Field): widget = widgets.HiddenInput() def __init__( self, label=None, validators=None, data_url=None, get_object=None, get_pk=None, coerce=int, get_label=None, allow_blank=False, blank_text='', **kwargs ): super(AjaxField, self).__init__(label, validators, **kwargs) if anyjson is None: raise ImproperlyConfigured( 'AjaxField requires anyjson extension to be installed.' ) if data_url is None: raise Exception('data_url must be given') self.get_pk = get_pk if get_label is None: self.get_label = lambda x: x elif isinstance(get_label, six.string_types): self.get_label = operator.attrgetter(get_label) else: self.get_label = get_label self.coerce = coerce self.data_url = data_url self.get_object = get_object self.allow_blank = allow_blank self.blank_text = blank_text @property def data(self): if self._formdata is not None: try: pk = self.coerce(self._formdata) except ValueError: self.data = None else: self.data = self.get_object(pk) return self._data @data.setter def data(self, data): self._data = data self._formdata = None def process_formdata(self, valuelist): if valuelist: if self.allow_blank and not valuelist[0]: self.data = None else: self._data = None self._formdata = valuelist[0] def pre_validate(self, form): if self.data is None: if self._formdata or not self.allow_blank: raise ValidationError('Not a valid choice') def __call__(self, **kwargs): kwargs.setdefault( 'data-allow-clear', anyjson.serialize(self.allow_blank) ) kwargs.setdefault('data-placeholder', self.blank_text) kwargs.setdefault('data-url', self.data_url) if self.data is not None: kwargs.setdefault('data-initial-label', self.get_label(self.data)) kwargs.setdefault('value', self.get_pk(self.data)) else: kwargs.setdefault('value', '') return super(AjaxField, self).__call__(**kwargs) wtforms-components-0.10.5/wtforms_components/fields/color.py000066400000000000000000000016751400106477700244040ustar00rootroot00000000000000from ..widgets import ColorInput from .html5 import StringField class ColorField(StringField): """ A string field representing a Color object from python colour package. .. _colours: https://github.com/vaab/colour Represents an ````. """ widget = ColorInput() error_msg = u'Not a valid color.' def _value(self): if self.raw_data: return self.raw_data[0] if self.data: return str(self.data) else: return u'' def process_formdata(self, valuelist): from colour import Color if valuelist: if valuelist[0] == u'' or valuelist[0] == '': self.data = None else: try: self.data = Color(valuelist[0]) except AttributeError: self.data = None raise ValueError(self.gettext(self.error_msg)) wtforms-components-0.10.5/wtforms_components/fields/html5.py000066400000000000000000000031401400106477700243040ustar00rootroot00000000000000try: from wtforms.fields.html5 import ( DateField, DateTimeField, DecimalField, DecimalRangeField, IntegerField, IntegerRangeField, SearchField ) except ImportError: # wtforms>=3 from wtforms.fields import ( DateField, DateTimeField, DecimalField, DecimalRangeField, IntegerField, IntegerRangeField, SearchField ) from wtforms.fields import StringField as _StringField from ..widgets import ( DateInput, DateTimeInput, DateTimeLocalInput, EmailInput, NumberInput, RangeInput, SearchInput, TextInput ) class EmailField(_StringField): widget = EmailInput() class IntegerField(IntegerField): widget = NumberInput(step='1') class DecimalField(DecimalField): widget = NumberInput(step='any') class DateTimeLocalField(DateTimeField): def __init__( self, label=None, validators=None, format='%Y-%m-%dT%H:%M:%S', **kwargs ): super(DateTimeLocalField, self).__init__( label, validators, format, **kwargs ) widget = DateTimeLocalInput() class DateTimeField(DateTimeField): widget = DateTimeInput() class DateField(DateField): widget = DateInput() class IntegerSliderField(IntegerRangeField): widget = RangeInput(step='1') class DecimalSliderField(DecimalRangeField): widget = RangeInput(step='any') class SearchField(SearchField): widget = SearchInput() class StringField(_StringField): widget = TextInput() wtforms-components-0.10.5/wtforms_components/fields/interval.py000066400000000000000000000031151400106477700251010ustar00rootroot00000000000000from intervals import ( DateInterval, DateTimeInterval, DecimalInterval, FloatInterval, IntervalException, IntInterval ) from .html5 import StringField class IntervalField(StringField): """ A string field representing an interval object from `intervals`_. .. _intervals: https://github.com/kvesteri/intervals """ def _value(self): if self.raw_data: return self.raw_data[0] if self.data: return self.data.hyphenized else: return u'' def process_formdata(self, valuelist): if valuelist: if valuelist[0] == u'' or valuelist[0] == '': self.data = None else: try: self.data = self.interval_class.from_string(valuelist[0]) except IntervalException: self.data = None raise ValueError(self.gettext(self.error_msg)) class DecimalIntervalField(IntervalField): error_msg = u'Not a valid decimal range value' interval_class = DecimalInterval class FloatIntervalField(IntervalField): error_msg = u'Not a valid float range value' interval_class = FloatInterval class IntIntervalField(IntervalField): error_msg = u'Not a valid int range value' interval_class = IntInterval class DateIntervalField(IntervalField): error_msg = u'Not a valid date range value' interval_class = DateInterval class DateTimeIntervalField(IntervalField): error_msg = u'Not a valid datetime range value' interval_class = DateTimeInterval wtforms-components-0.10.5/wtforms_components/fields/json_field.py000066400000000000000000000014551400106477700253760ustar00rootroot00000000000000import json from wtforms import fields, widgets class JSONField(fields.StringField): """ A text field which stores a `json`. """ widget = widgets.TextArea() def _value(self): return json.dumps(self.data) if self.data else '' def process_formdata(self, valuelist): if valuelist: try: self.data = json.loads(valuelist[0]) except ValueError: self.data = None raise ValueError('This field contains invalid JSON') else: self.data = None def pre_validate(self, form): if self.data: try: json.dumps(self.data) except TypeError: self.data = None raise ValueError('This field contains invalid JSON') wtforms-components-0.10.5/wtforms_components/fields/passive_hidden.py000066400000000000000000000003071400106477700262420ustar00rootroot00000000000000from wtforms.fields import HiddenField class PassiveHiddenField(HiddenField): """ HiddenField that does not populate obj values. """ def populate_obj(self, obj, name): pass wtforms-components-0.10.5/wtforms_components/fields/select.py000066400000000000000000000041701400106477700245360ustar00rootroot00000000000000from copy import copy from wtforms import SelectField as _SelectField from wtforms.validators import ValidationError from ..widgets import SelectWidget class SelectField(_SelectField): """ Add support of ``optgroup``'s' to default WTForms' ``SelectField`` class. So, next choices would be supported as well:: ( ('Fruits', ( ('apple', 'Apple'), ('peach', 'Peach'), ('pear', 'Pear') )), ('Vegetables', ( ('cucumber', 'Cucumber'), ('potato', 'Potato'), ('tomato', 'Tomato'), )) ) Also supports lazy choices (callables that return an iterable) """ widget = SelectWidget() def __init__(self, *args, **kwargs): choices = kwargs.pop('choices', None) if callable(choices): super(SelectField, self).__init__(*args, **kwargs) self.choices = copy(choices) else: super(SelectField, self).__init__(*args, choices=choices, **kwargs) def iter_choices(self): """ We should update how choices are iter to make sure that value from internal list or tuple should be selected. """ for value, label in self.concrete_choices: yield (value, label, (self.coerce, self.data)) @property def concrete_choices(self): if callable(self.choices): return self.choices() return self.choices @property def choice_values(self): values = [] for value, label in self.concrete_choices: if isinstance(label, (list, tuple)): for subvalue, sublabel in label: values.append(subvalue) else: values.append(value) return values def pre_validate(self, form): """ Don't forget to validate also values from embedded lists. """ values = self.choice_values if (self.data is None and u'' in values) or self.data in values: return True raise ValidationError(self.gettext(u'Not a valid choice')) wtforms-components-0.10.5/wtforms_components/fields/select_multiple.py000066400000000000000000000025321400106477700264510ustar00rootroot00000000000000from wtforms.validators import ValidationError from ..widgets import SelectWidget from .select import SelectField class SelectMultipleField(SelectField): """ No different from a normal select field, except this one can take (and validate) multiple choices. You'll need to specify the HTML `rows` attribute to the select field when rendering. """ widget = SelectWidget(multiple=True) def process_data(self, value): try: self.data = list(self.coerce(v) for v in value) except (ValueError, TypeError): self.data = None def process_formdata(self, valuelist): try: self.data = list(self.coerce(x) for x in valuelist) except ValueError: raise ValueError( self.gettext( 'Invalid choice(s): one or more data inputs ' 'could not be coerced' ) ) def pre_validate(self, form): if self.data: values = self.choice_values for value in self.data: if value not in values: raise ValidationError( self.gettext( "'%(value)s' is not a valid" " choice for this field" ) % dict(value=value) ) wtforms-components-0.10.5/wtforms_components/fields/split_date_time.py000066400000000000000000000036771400106477700264400ustar00rootroot00000000000000import datetime from wtforms import Form from wtforms.fields import FormField from .html5 import DateField from .time import TimeField try: from wtforms.utils import unset_value as _unset_value except ImportError: from wtforms.fields import _unset_value class Date(): date = None time = None class SplitDateTimeField(FormField): def __init__(self, label=None, validators=None, separator='-', **kwargs): FormField.__init__( self, datetime_form(kwargs.pop('datetime_form', {})), label=label, validators=validators, separator=separator, **kwargs ) def process(self, formdata, data=_unset_value, extra_filters=None): if data is _unset_value: try: data = self.default() except TypeError: data = self.default if data: obj = Date() obj.date = data.date() obj.time = data.time() else: obj = None kwargs = dict() if extra_filters is not None: # do not enforce extra_filters=None injection to wtforms<3 kwargs['extra_filters'] = extra_filters FormField.process(self, formdata, data=obj, **kwargs) def populate_obj(self, obj, name): if hasattr(obj, name): date = self.date.data hours, minutes = self.time.data.hour, self.time.data.minute setattr(obj, name, datetime.datetime( date.year, date.month, date.day, hours, minutes )) def datetime_form(options): options.setdefault('date', {}) options.setdefault('time', {}) options['date'].setdefault('label', u'Date') options['time'].setdefault('label', u'Time') base_form = options.get('base_form', Form) class DateTimeForm(base_form): date = DateField(**options['date']) time = TimeField(**options['time']) return DateTimeForm wtforms-components-0.10.5/wtforms_components/fields/time.py000066400000000000000000000020631400106477700242140ustar00rootroot00000000000000from __future__ import absolute_import import datetime import time from wtforms.fields import Field from ..widgets import TimeInput class TimeField(Field): """ A text field which stores a `datetime.time` matching a format. """ widget = TimeInput() error_msg = 'Not a valid time.' def __init__(self, label=None, validators=None, format='%H:%M', **kwargs): super(TimeField, self).__init__(label, validators, **kwargs) self.format = format def _value(self): if self.raw_data: return ' '.join(self.raw_data) elif self.data is not None: return self.data.strftime(self.format) else: return '' def process_formdata(self, valuelist): if valuelist: time_str = ' '.join(valuelist) try: self.data = datetime.time( *time.strptime(time_str, self.format)[3:6] ) except ValueError: self.data = None raise ValueError(self.gettext(self.error_msg)) wtforms-components-0.10.5/wtforms_components/utils.py000066400000000000000000000016231400106477700231510ustar00rootroot00000000000000import six def is_scalar(value): return isinstance(value, (type(None), six.string_types, int, float, bool)) def null_or_unicode(value): return six.text_type(value) or None def null_or_int(value): try: return int(value) except TypeError: return None class Chain(object): """ Generic chain class. Very similar to itertools.chain except this object can be iterated over multiple times. """ def __init__(self, *iterables): self.iterables = iterables def __iter__(self): for iterable in self.iterables: for value in iterable: yield value def __contains__(self, value): return any(value in iterable for iterable in self.iterables) def __len__(self): return sum(map(len, self.iterables)) def __repr__(self): return '%s(%r)' % (self.__class__.__name__, list(self.iterables)) wtforms-components-0.10.5/wtforms_components/validators.py000066400000000000000000000141251400106477700241620ustar00rootroot00000000000000from __future__ import absolute_import from wtforms import ValidationError from wtforms.validators import StopValidation try: from validators import email except ImportError: from validators import is_email as email class ControlStructure(object): """ Base object for validator control structures """ message = None def reraise(self, exc): if not self.message: raise exc else: raise type(exc)(self.message) class Chain(ControlStructure): """ Represents a chain of validators, useful when using multiple validators with If control structure. :param validators: list of validator objects :param message: custom validation error message, if this message is set and some of the child validators raise a ValidationError, an exception is being raised again with this custom message. """ def __init__(self, validators, message=None): self.validators = validators if message: self.message = message def __call__(self, form, field): for validator in self.validators: try: validator(form, field) except ValidationError as exc: self.reraise(exc) except StopValidation as exc: self.reraise(exc) class If(ControlStructure): """ Conditional validator. :param condition: callable which takes two arguments form and field :param validator: encapsulated validator, this validator is validated only if given condition returns true :param message: custom message, which overrides child validator's validation error message """ def __init__(self, condition, validator, message=None): self.condition = condition self.validator = validator if message: self.message = message def __call__(self, form, field): if self.condition(form, field): try: self.validator(form, field) except ValidationError as exc: self.reraise(exc) except StopValidation as exc: self.reraise(exc) class BaseDateTimeRange(object): def __init__(self, min=None, max=None, format='%H:%M', message=None): self.min = min self.max = max self.format = format self.message = message def __call__(self, form, field): data = field.data min_ = self.min() if callable(self.min) else self.min max_ = self.max() if callable(self.max) else self.max if (data is None or (min_ is not None and data < min_) or (max_ is not None and data > max_)): if self.message is None: if max_ is None: self.message = field.gettext(self.greater_than_msg) elif min_ is None: self.message = field.gettext(self.less_than_msg) else: self.message = field.gettext(self.between_msg) raise ValidationError( self.message % dict( field_label=field.label, min=min_.strftime(self.format) if min_ else '', max=max_.strftime(self.format) if max_ else '' ) ) class TimeRange(BaseDateTimeRange): """ Same as wtforms.validators.NumberRange but validates date. :param min: The minimum required value of the time. If not provided, minimum value will not be checked. :param max: The maximum value of the time. If not provided, maximum value will not be checked. :param message: Error message to raise in case of a validation error. Can be interpolated using `%(min)s` and `%(max)s` if desired. Useful defaults are provided depending on the existence of min and max. """ greater_than_msg = u'Time must be greater than %(min)s.' less_than_msg = u'Time must be less than %(max)s.' between_msg = u'Time must be between %(min)s and %(max)s.' def __init__(self, min=None, max=None, format='%H:%M', message=None): super(TimeRange, self).__init__( min=min, max=max, format=format, message=message ) class DateRange(BaseDateTimeRange): """ Same as wtforms.validators.NumberRange but validates date. :param min: The minimum required value of the date. If not provided, minimum value will not be checked. :param max: The maximum value of the date. If not provided, maximum value will not be checked. :param message: Error message to raise in case of a validation error. Can be interpolated using `%(min)s` and `%(max)s` if desired. Useful defaults are provided depending on the existence of min and max. """ greater_than_msg = u'Date must be greater than %(min)s.' less_than_msg = u'Date must be less than %(max)s.' between_msg = u'Date must be between %(min)s and %(max)s.' def __init__(self, min=None, max=None, format='%Y-%m-%d', message=None): super(DateRange, self).__init__( min=min, max=max, format=format, message=message ) class Email(object): """ Validates an email address. This validator is based on `Django's email validator`_ and is stricter than the standard email validator included in WTForms. .. _Django's email validator: https://github.com/django/django/blob/master/django/core/validators.py :param message: Error message to raise in case of a validation error. :copyright: (c) Django Software Foundation and individual contributors. :license: BSD """ domain_whitelist = ['localhost'] def __init__(self, message=None, whitelist=None): self.message = message if whitelist is not None: self.domain_whitelist = whitelist def __call__(self, form, field): if not email(field.data, self.domain_whitelist): if self.message is None: self.message = field.gettext(u'Invalid email address.') raise ValidationError(self.message) wtforms-components-0.10.5/wtforms_components/widgets.py000066400000000000000000000155221400106477700234620ustar00rootroot00000000000000from copy import copy import six from wtforms.validators import DataRequired, NumberRange from wtforms.widgets import html_params, Input from wtforms.widgets import Select as _Select from ._compat import html_escape, HTMLString from .validators import DateRange, TimeRange def min_max(field, validator_class): """ Returns maximum minimum and minimum maximum value for given validator class of given field. :param field: WTForms Field object :param validator_class: WTForms Validator class Example:: class MyForm(Form): some_integer_field = IntegerField( validators=[Length(min=3, max=6), Length(min=4, max=7)] ) form = MyForm() min_max(form.some_integer_field, Length) # {'min': 4, 'max': 6} """ min_values = [] max_values = [] for validator in field.validators: if isinstance(validator, validator_class): if validator.min is not None: min_values.append(validator.min) if validator.max is not None: max_values.append(validator.max) data = {} if min_values: data['min'] = max(min_values) if max_values: data['max'] = min(max_values) return data def has_validator(field, validator_class): """ Returns whether or not given field has an instance of given validator class in the validators property. :param field: WTForms Field object :param validator_class: WTForms Validator class """ return any([ isinstance(validator, validator_class) for validator in field.validators ]) class HTML5Input(Input): def __init__(self, **kwargs): self.options = kwargs def __call__(self, field, **kwargs): if has_validator(field, DataRequired): kwargs.setdefault('required', True) for key, value in self.range_validators(field).items(): kwargs.setdefault(key, value) if hasattr(field, 'widget_options'): for key, value in self.field.widget_options: kwargs.setdefault(key, value) options_copy = copy(self.options) options_copy.update(kwargs) return super(HTML5Input, self).__call__(field, **options_copy) def range_validators(self, field): return {} class BaseDateTimeInput(HTML5Input): """ Base class for TimeInput, DateTimeLocalInput, DateTimeInput and DateInput widgets """ range_validator_class = DateRange def range_validators(self, field): data = min_max(field, self.range_validator_class) if 'min' in data: data['min'] = data['min'].strftime(self.format) if 'max' in data: data['max'] = data['max'].strftime(self.format) return data class TextInput(HTML5Input): input_type = 'text' class SearchInput(HTML5Input): """ Renders an input with type "search". """ input_type = 'search' class MonthInput(HTML5Input): """ Renders an input with type "month". """ input_type = 'month' class WeekInput(HTML5Input): """ Renders an input with type "week". """ input_type = 'week' class RangeInput(HTML5Input): """ Renders an input with type "range". """ input_type = 'range' class URLInput(HTML5Input): """ Renders an input with type "url". """ input_type = 'url' class ColorInput(HTML5Input): """ Renders an input with type "color". """ input_type = 'color' class TelInput(HTML5Input): """ Renders an input with type "tel". """ input_type = 'tel' class EmailInput(HTML5Input): """ Renders an input with type "email". """ input_type = 'email' class TimeInput(BaseDateTimeInput): """ Renders an input with type "time". Adds min and max html5 field parameters based on field's TimeRange validator. """ input_type = 'time' range_validator_class = TimeRange format = '%H:%M:%S' class DateTimeLocalInput(BaseDateTimeInput): """ Renders an input with type "datetime-local". Adds min and max html5 field parameters based on field's DateRange validator. """ input_type = 'datetime-local' format = '%Y-%m-%dT%H:%M:%S' class DateTimeInput(BaseDateTimeInput): """ Renders an input with type "datetime". Adds min and max html5 field parameters based on field's DateRange validator. """ input_type = 'datetime' format = '%Y-%m-%dT%H:%M:%SZ' class DateInput(BaseDateTimeInput): """ Renders an input with type "date". Adds min and max html5 field parameters based on field's DateRange validator. """ input_type = 'date' format = '%Y-%m-%d' class NumberInput(HTML5Input): """ Renders an input with type "number". Adds min and max html5 field parameters based on field's NumberRange validator. """ input_type = 'number' range_validator_class = NumberRange def range_validators(self, field): return min_max(field, self.range_validator_class) class ReadOnlyWidgetProxy(object): def __init__(self, widget): self.widget = widget def __getattr__(self, name): return getattr(self.widget, name) def __call__(self, field, **kwargs): kwargs.setdefault('readonly', True) # Some html elements also need disabled attribute to achieve the # expected UI behaviour. kwargs.setdefault('disabled', True) return self.widget(field, **kwargs) class SelectWidget(_Select): """ Add support of choices with ``optgroup`` to the ``Select`` widget. """ @classmethod def render_optgroup(cls, value, label, mixed): children = [] for item_value, item_label in label: item_html = cls.render_option(item_value, item_label, mixed) children.append(item_html) html = u'%s' data = (html_escape(six.text_type(value)), u'\n'.join(children)) return HTMLString(html % data) @classmethod def render_option(cls, value, label, mixed): """ Render option as HTML tag, but not forget to wrap options into ``optgroup`` tag if ``label`` var is ``list`` or ``tuple``. """ if isinstance(label, (list, tuple)): return cls.render_optgroup(value, label, mixed) try: coerce_func, data = mixed except TypeError: selected = mixed else: if isinstance(data, list) or isinstance(data, tuple): selected = coerce_func(value) in data else: selected = coerce_func(value) == data options = {'value': value} if selected: options['selected'] = True html = u'' data = (html_params(**options), html_escape(six.text_type(label))) return HTMLString(html % data)