Package: tri.form
Warningtri.form is end of life. It has been merged intoiommi.iommi is backwards incompatible but the porting effort should be fairly mild,
the biggest changes are thatshowis now calledincludeand plural is used
consistently for containers (sofield__fooisfields__fooin iommi).tri.formtri.form is alternative forms library for Django and Flask. It is inspired by, and comes from a frustration with, the standard Django forms.Major features compared to Django forms:Supports__syntax for going across table/object boundaries, similar to how Django does with QuerySets.Send in a callable that is late evaluated to determine if a field should be displayed (show). This is very handy for showing a slightly different form to administrators for example.Easy configuration without writing entire classes that are only used in one place anyway.ExampleYou can either create a subclass ofForm…classUserForm(Form):name=Field.text()username=Field.text(is_valid=lambdaform,field,parsed_data:parsed_data.startswith('demo_'))is_admin=Field.boolean(show=lambdaform,field:form.request.user.is_staff,# show only for stafflabel_template='tweak_label_tag.html')defedit_user_view(request,username):form=UserForm(request=request)user=User.objects.get(username=username)ifform.is_valid()andrequest.method=='POST':form.apply(user)user.save()returnHttpRedirect('..')returnrender(template_name='edit_user.html',context_instance=RequestContext(request,{'form':form}))<!-- edit_user.html --><formaction=""method="post">{% csrf_token %}<div><table>{{ form }}</table></div><inputtype="submit"value="Save"/></form>or just instantiate aFormwith aFieldlist and use it directly:defedit_user_view(request,username):form=Form(fields=[Field.text(name='name',is_valid=lambdaform,field,parsed_data:parsed_data.startswith('demo_')),Field.text(name='username'),Field.boolean(name='is_admin',show=lambdaform,field:form.request.user.is_staff,# show only for stafflabel_template='tweak_label_tag.html',)])# rest of view function...You can also generate forms from Django models automatically (but still change the behavior!). The above example
is equivalent to:defedit_user_view(request,username):form=Form.from_model(request.POST,User,# the field 'name' is generated automatically and we are fine with the defaultsusername__is_valid=lambdaform,field,parsed_data:parsed_data.startswith('demo_'),is_admin__label_template='tweak_label_tag.html',is_admin__show=lambdaform,field:form.request.user.is_staff)# show only for staff# rest of view function...or even better: usetri.form.views.create_or_edit_object:defedit_user_view(request,username):returncreate_or_edit_object(request,model=User,is_create=False,instance=User.objects.get(username=username),form__username__is_valid=lambdaform,field,parsed_data:parsed_data.startswith('demo_'),form__is_admin__label_template='tweak_label_tag.html',form__is_admin__show=lambdaform,field:form.request.user.is_staff)# show only for staff# no html template! tri.form has a nice default for you :Ptri.form pre-packages sets of defaults for common field types as ‘shortcuts’. Some examples includeField.boolean,Field.integerandField.choice. The full list of shortcuts can be found in theAPI documentation for Field.Running testsYou need tox installed then justmake test.LicenseBSDDocumentationhttp://triform.readthedocs.org.Changelog7.5.0 (2020-04-24)Upped dependency tri.declarative to 5.x7.4.0 (2020-01-30)Fix name attribute on submit action on edit_or_create forms to work with form.is_target() when the form has a name7.3.1 (2019-12-18)You can now customize the ajax dispatch page size by settingextra__endpoint_page_sizeon a fieldRemoved validation onendpoint_dispatch_prefixbecause in some cases we do want them to be out of sync (tri.table does this for example)7.3.0 (2019-12-06)Fieldwas missing the@with_metadecoratornewformsclass onFormremoved. It was turned on by mistake due to some heritage from the code base tri.form was extracted from.Fixed an issue where overriding a Field didn’t work when creating a form from a modelUse select2 by default forchoice_querysetMissingUUIDFieldfactoryYou can now override field properties like this:MyForm(field__foo__query__show=True)Fix ajax dispatch, and namespacing when multiple forms are present on the page7.2.4 (2019-10-23)Treat actions dicts as Namespaces7.2.3 (2019-10-15)Fixed deprecation warnings7.2.2 (2019-10-11)Fixed a bug whereActionwas functionally bound toForm, but it should be generally useful (e.g. for tri.table).Fixed a bug withField.iconwhere there was a missing space when using theicon_classesargument, causing garbled css classes.7.2.1 (2019-10-10)Fixed a bug where non-named forms did not perform validation because they didn’t find the/POST key. They shouldn’t need that!7.2.0 (2019-10-10)Add support for setting name on forms to be able to reuse field names between two forms in the same viewRemoved deprecatedrender_css_classes,render_container_css_classes,render_label_container_css_classesandrender_input_container_css_classesFixed various issues with the namespacing necessary to have multiple forms on one page.Introducedactions/Actionthat will replacelinks/Link.Deprecatedlinks/Link.create_or_edit_objectnow has an overridable parameteron_valid_post.7.1.0 (2019-09-20)Added declared_fields toForm.7.0.0 (2019-06-10)Renamed package fromtri.formtotri_form. This is a breaking changeDropped python2 supportDropped Django < 2.0 support6.0.2 (2019-06-03)Changed the default value forparse_emtpy_string_as_noneto be based on the model fieldsnullproperty.from_modelshould not overwrite defaults too earlyField.choicenow has a sane default parser usingchoice_to_optionChanged render_attrs to stop you from making some common mistakesFixedtime_render_value()Fixes and improved tests for from_model_expandFixedfrom_modelfor DjangoTextField. Should beField.textarea, notField.text6.0.1 (2019-05-06)Fixed cases where from_model lost the type when inheriting6.0.0 (2019-04-12)MakeFieldshortcuts compatible with subclassing. Previous fix didn’t work all the way.Use the new major tri.declarative, and update to follow the new style of class member shortcutsMajor fixes to howfrom_modelworks. SubclassingFormandFieldnow works like you’d expect. This is a breaking change.RemovedField.comma_separatedshortcut. This was never used, and poorly tested.5.4.0 (2019-04-01)MakeFieldshortcuts compatible with subclassing5.3.1 (2019-03-20)Fix that Django’s DoesNotExist events don’t leak out of the field-validation code5.3.0 (2019-02-18)If you subclass Form this custom class is now used properly in thefrom_modelcode pathsFormnow has a refinable attributefield_classwhich you should use to point to yourFieldsubclass if you have one. This is best accomplished in theMetaclass on the class inheriting fromForm.AddedForm.create_or_edit_objectthat will respect your subclass if you have one.5.2.2 (2019-01-28)Fixed escaping bug introduced in 5.2.0: You could get a KeyError crash if you had{and}in attributes.5.2.1 (2019-01-16)Fixed coverage build (this also broke the travis build and as a consequence the pypi release process)5.2.0 (2019-01-16)Rendering of submit button is now aLinkand you can now supply your own buttons and links here.Fixed crash in rendering fields in some cases. This was due to an incorrect use offormat_html.Flask and Jinja2 supportUpdated examples for modern django, and added an exampleModernize attrs rendering on Field (this introduces a few deprecations)render_attrs support for style attributes. This means you can now doLink(attrs__style__display=’none’)for example.5.1.1 (2018-10-23)File field tried to render the binary contents on form validation errors. This is a crash in Django 2.1from_modelwas broken when traversing a foreign key relation with__5.1.0 (2018-10-09)Dropped Django 1.8 supportFixed deprecation warnings for Django 2.05.0.12 (2018-10-03)AddedField.boolean_tristatefor editing boolean fields with null value allowed5.0.11 (2018-09-21)SimplifiedMISSINGdefinition5.0.10 (2018-06-29)Fix evaluation of Link attributes5.0.9 (2018-06-19)Fixed python3 compability for release check.Fixed release check on shallow git clone5.0.8 (2018-06-19)Fixed release functionality5.0.7 (2018-06-18)Stepped tri.declarative dependency.5.0.6 (2018-06-15)Fix non-editable mode on multi_choice fields.member_from_model support for __ paths.MadeLinkattributes lazy on form parameter.5.0.5 (2018-04-11)Fix form submit link rendering.5.0.4 (2017-10-16)Revert new default parser onField.choice.5.0.3 (2017-10-16)Improve default parser implementation onField.choice. A reasonable implementation of__str__is enough for objects inchoices.Fix evaluation order so thatField.initial/Field.initial_listis available when fields are evaluated. (Field.showis still invoked early)5.0.2 (2017-10-06)Field.from_modelproduced incorrect parser for foreign keys.5.0.1 (2017-09-15)Correctly check unique constraints when editing objectBug whereform.instancewas set too late inFormconstructor, resulting inAttributeErrorin certain lambdas5.0.0 (2017-08-22)Refactored to use new tri.declarative: usingRefinableObject,Shortcut, and the newcall_targetparameter ofNamespaceChanged dispatch separator from__to/ChangedlabelonFieldtodisplay_name. This is in line with tri.query and tri.table.Field.choiceincorrectly handles post_validation (fixes github issue #9)Formnow doesn’t try to read initial data and form data from Fields that are show=Falsecreate_or_edit_objectdoesn’t take a parameterrender_contextanymore, userender__contextYou no longer need to specify themodelparameter tochoice_querysetormulti_choice_querysetif you give it aQuerySetaschoices(as opposed to giving a callable)Field.choice_querysetandField.multi_choice_querysetnow reevaluates the QuerySet on each usage (fixes tri.table github issue 16)4.10.1 (2017-06-20)Bugfix:on_savecallback forcreate_or_edit_objectwas missingformparameter4.10.0 (2017-06-12)Fixed bug where namespaced form was not rendered when the other namespaced form had an error4.9.0 (2017-05-31)Added attribute ‘name’ to Form in order to namespace POSTs in cases where there are more than one form4.8.0 (2017-05-23)Added useful return value onForm.apply(…)Improve repr onFieldAddedForm.editablesettings for setting all fields at once4.7.1 (2017-04-24)Bugfix for endpoint dispatch: we must allow a result to be an empty list/dict4.7.0 (2017-04-24)AddedLinkclass, and redefined the submit button on the form in terms of aLinkFixed incorrect handling of template rendering andRequestContextbetween django before and after 1.10Dropped official support of django 1.7Addedattrsmember onForm, and added methodrender_attrsthat you use to render the attributes into htmlAdded six as a dependency4.6.2 (2017-04-18)Fixedrender_attrsto escape quotation marks4.6.1 (2017-04-11)Fixed non-editable fields so that you can override the renderingFixed bug where raw_data was sent to render_value when there was an error on the field4.6.0 (2017-03-15)Fieldclass now inherits fromobject, making the implementation more pythonic.
(Attributes still possible to override in constructor call, seeNamespaceAwareObject)AddedForm.extranamespace for custom data.4.5.0 (2016-12-19)Addraw_dataandraw_data_listattributes toFielddefinition to enable custom handling on django file download4.4.0 (2016-12-13)Set instance on form just after save to be able to use newly created pk in a redirect4.3.1 (2016-12-08)Prevent code from running on import4.3.0 (2016-10-20)Lazy evaluation of select choices.4.2.0 (2016-10-06)Addendpointnamespace toFormandFieldconstructor to add custom endpoint callbacks.Addconfigandvalidateendpoint implementations4.1.0 (2016-09-20)Fix formatting of form field error output when there are multiple field errorsFix bug in form validation signaling required field missing on choices where the value is falsy, e.g. 0Implement djangos uniqueness validation on save in forms/views.pyFixed input type on url field4.0.0 (2016-09-14)Improved handling offrom_model. You can now do the following without issues:form=Form.from_model(field__foo__class=Form.integer)The incorrectly named parameterdb_fieldtoForm.fields_from_modelhas been renamed to the correctfield.The parameterdb_fieldtocreate_members_from_modelhas been renamed tomember_params_by_member_name.Better logic for figuring out which mode we’re in when POST-ingAllowNoneasendpoint_dispatch_prefix.3.8.0 (2016-09-12)Fixed namespace dispatch bugs increate_or_edit_object3.7.0 (2016-08-17)Compatible with Django 1.9 & 1.103.6.0 (2016-08-16)Field.datetime is more forgiving in the formats it receives: it will not accept ISO8601 formats but missing seconds or seconds+minutesField.boolean field didn’t respect specified input_templateInputs that were parsed to lists where the field was a list now works properly: None is not passed to the validation function.Fixed pypi rendering of documentationMore honest coverage numbers3.5.0 (2016-06-16)Addedis_full_formparameter to form to optionally control the rendering of the “-“=”-” marker form field3.4.0 (2016-06-15)Added better error messages when missing django model mappingsFix population of read-only fields from initial value3.3.0 (2016-06-02)bugfixes3.2.0 (2016-05-26)default_help_text should not blow up on invalid referencesRemoved some dead code3.1.0 (2016-05-26)Fixed confusing naming of Field.text to Field.textareaSupport for ajax backend. New parameters to Field: endpoint_path and endpoint_dispatch. For now only implemented for Field.choice_queryset and tailored for select2. To use it: specify template_name=’tri_form/choice_select2.html’.3.0.0 (2016-05-26)Parse modes introduced. This fixes validation of partially submitted forms, using tri.form for filters and other problems.Refactored to use tri.declarative @dispatchAdded __field__ endpoint handling. This is useful for e.g. loading choices with ajax instead of up front.Form.errors is now a setviews.create_object/edit_object/create_or_edit_object now default parameterrenderto render_to_response instead of render_to_string. This is a potential braking change.2.2.0 (2016-04-25)Minor bugfix for fields-from-model handling of auto fields2.1.0 (2016-04-20)Fix broken blank field value on fields from django model when django model
blank setting is True.2.0.0 (2016-04-18)Changed Form.from_model method to require database field kwargs underfield__namespace. This is a breaking change.Fixed saving of foreign keys in django create viewEnable mixing column definitions in both declared fields and class meta.1.16.0 (2016-04-15)Fix table mode render in python 21.15.0 (2016-04-08)Fixed radio button render1.14.0 (2016-04-01)Added python 3 supportAdded render helper functions for reuse by tri.table et al1.13.0 (2016-03-10)Fixed many_to_one field1.12.0 (2016-03-03)Add support for Django 1.81.11.0 (2016-02-29)Datetime fields used to not roundtrip cleanly via the form (they output
milliseconds then failed on parsing them) Field.file didn’t exist.Changed syntax for specifying html attributes and classes. They are now use
the same way of addressing as other things, e.g.:
Field.choice(attrs__foo=”bar”, attrs__class__baz=True) will yield something
like<select … class=”baz” foo=bar>…</select>1.10.0 (2016-02-08)Made sure form validation is only run onceFixed input form class and render context to create_or_edit_object view1.9.0 (2016-01-15)Fixed default value initialization on Field attributes to not reuse containers.Added support for ManyToManyField when generating forms for model objects.Added ‘read_from_instance’ and ‘write_to_instance’ callbacks for customized instance marshalling.1.8.0 (2016-01-13)Bugfix release.Added missing ‘after’ attribute on Field prohibiting form order customizationFixed default value handling of ‘attr’ to make None a valid value when no attribute should be read.Fixed CSS handling on required fields.1.7.0 (2016-01-13)Made evaluation of choices lazy even when there is a None alternative.