Skip to main content

tri.form is a form library

Project description

https://travis-ci.org/TriOptima/tri.form.svg?branch=master http://codecov.io/github/TriOptima/tri.form/coverage.svg?branch=master

tri.form

tri.form is alternative forms library for Django. 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 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.

Example

You can either create a subclass of Form

class UserForm(Form):
    name = Field.text()
    username = Field.text(is_valid=lambda form, field, parsed_data: parsed_data.startswith('demo_'))
    is_admin = Field.boolean(
        show=lambda form, field: form.request.user.is_staff, # show only for staff
        label_template='tweak_label_tag.html')

def edit_user_view(request, username):
    form = UserForm(request=request)

    user = User.objects.get(username=username)
    if form.is_valid() and request.method == 'POST':
        form.apply(user)
        user.save()
        return HttpRedirect('..')

    return render(
        template_name='edit_user.html',
        context_instance=RequestContext(request, {'form': form}))
<!-- edit_user.html -->
<form action="" method="post">{% csrf_token %}
  <div>
    <table>
      {{ form }}
    </table>
  </div>
  <input type="submit" value="Save" />
</form>

or just instantiate a Form with a Field list and use it directly:

def edit_user_view(request, username):
    form = Form(fields=[
        Field.text(
            name='name',
            is_valid=lambda form, field, parsed_data: parsed_data.startswith('demo_')),
        Field.text(name='username'),
        Field.boolean(
            name='is_admin',
            show=lambda form, field: form.request.user.is_staff, # show only for staff
            label_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:

def edit_user_view(request, username):
    form = Form.from_model(
        request.POST,
        User,
        # the field 'name' is generated automatically and we are fine with the defaults
        username__is_valid=lambda form, field, parsed_data: parsed_data.startswith('demo_'),
        is_admin__label_template='tweak_label_tag.html',
        is_admin__show=lambda form, field: form.request.user.is_staff) # show only for staff

    # rest of view function...

or even better: use tri.form.views.create_or_edit_object:

def edit_user_view(request, username):
    return create_or_edit_object(
        request,
        model=User,
        is_create=False,
        instance=User.objects.get(username=username),

        form__username__is_valid=lambda form, field, parsed_data: parsed_data.startswith('demo_'),
        form__is_admin__label_template='tweak_label_tag.html',
        form__is_admin__show=lambda form, field: form.request.user.is_staff) # show only for staff
    # no html template! tri.form has a nice default for you :P

tri.form pre-packages sets of defaults for common field types as ‘shortcuts’. Some examples include Field.boolean, Field.integer and Field.choice. The full list of shortcuts can be found in the API documentation for Field.

Running tests

You need tox installed then just make test.

License

BSD

Documentation

http://triform.readthedocs.org.

Changelog

3.7.0 (2016-08-17)

  • Compatible with Django 1.9 & 1.10

3.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+minutes

  • Field.boolean field didn’t respect specified input_template

  • Inputs 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 documentation

  • More honest coverage numbers

3.5.0 (2016-06-16)

  • Added is_full_form parameter to form to optionally control the rendering of the “-“=”-” marker form field

3.4.0 (2016-06-15)

  • Added better error messages when missing django model mappings

  • Fix population of read-only fields from initial value

3.3.0 (2016-06-02)

  • bugfixes

3.2.0 (2016-05-26)

  • default_help_text should not blow up on invalid references

  • Removed some dead code

3.1.0 (2016-05-26)

  • Fixed confusing naming of Field.text to Field.textarea

  • Support 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 @dispatch

  • Added __field__ endpoint handling. This is useful for e.g. loading choices with ajax instead of up front.

  • Form.errors is now a set

  • views.create_object/edit_object/create_or_edit_object now default parameter render to 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 fields

2.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 under field__ namespace. This is a breaking change.

  • Fixed saving of foreign keys in django create view

  • Enable mixing column definitions in both declared fields and class meta.

1.16.0 (2016-04-15)

  • Fix table mode render in python 2

1.15.0 (2016-04-08)

  • Fixed radio button render

1.14.0 (2016-04-01)

  • Added python 3 support

  • Added render helper functions for reuse by tri.table et al

1.13.0 (2016-03-10)

  • Fixed many_to_one field

1.12.0 (2016-03-03)

  • Add support for Django 1.8

1.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 once

  • Fixed input form class and render context to create_or_edit_object view

1.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 customization

  • Fixed 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.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

tri.form-3.7.0.tar.gz (20.8 kB view hashes)

Uploaded Source

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page