Forms Module

Forms

class fusionbox.forms.BaseChangeListForm(*args, **kwargs)[source]

Base class for all ChangeListForms.

get_queryset()[source]

If the form was initialized with a queryset, this method returns that queryset. Otherwise it returns Model.objects.all() for whatever model was defined for the form.

class fusionbox.forms.SearchForm(*args, **kwargs)[source]

Base form class for implementing searching on a model.

# Example Usage

class UserSearchForm(SearchForm):
    SEARCH_FIELDS = ('username', 'email', 'profile__role')
    model = User
>>> form = UserSearchForm(request.GET, queryset=User.objects.filter(is_active=True))
>>> form
<accounts.forms.UserSearchForm object at 0x102ea18d0>
>>> form.get_queryset()
[<User: admin>, <User: test@test.com>, <User: test2@test.com>]

SEARCH_FIELDS should be an iterable of valid django queryset field lookups. Lookups can span foreign key relationships.

By default, searches will be case insensitive. Set CASE_SENSITIVE to True to make searches case sensitive.

get_queryset()[source]

Constructs an ‘__contains’ or ‘__icontains’ filter across all of the fields listed in SEARCH_FIELDS.

Hook for modifying the queryset after the search. Will not be called on an invalid form.

Runs only if the form validates.

Hook for modifying the queryset prior to the search

Runs prior to any searching and is run regardless form validation.

class fusionbox.forms.FilterForm(*args, **kwargs)[source]

Base class for implementing filtering on a model.

# Example Usage

class UserFilterForm(FilterForm):
    FILTERS = {
        'active': 'is_active',
        'date_joined': 'date_joined__gte',
        'published': None, # Custom filtering
        }
    model = User

    PUBLISHED_CHOICES = (
            ('', 'All'),
            ('before', 'Before Today'),
            ('after', 'After Today'),
            )

    active = forms.BooleanField(required=False)
    date_joined = forms.DateTimeField(required=False)
    published = forms.ChoiceField(choices=PUBLISHED_CHOICES, widget=forms.HiddenInput())

    def pre_filter(self, queryset):
        published = self.cleaned_data.get('published')
        if published == '':
            return queryset
        elif published == 'before':
            return queryset.filter(published_at__lte=datetime.datetime.now())
        elif published == 'after':
            return queryset.filter(published_at__gte=datetime.datetime.now())

FILTERS defines a mapping of form fields to queryset filters.

When displaying in the template, this form also provides you with url querystrings for all of your filters.

form.filters is a dictionary of all of the filters defined on your form.

In the example above, you could do the following in the template for display links for the published filter

{% for choice in form.filters.published %}
    {% if choice.active %}
        {{ choice.display }} (<a href='?{{ choice.remove }}'>remove</a>)
    {% else %}
        <a href='?{{ choice.querystring }}'>{{ choice.display }}</a>
    {% endif %}
{% endfor %}
filters

Generates a dictionary of filters with proper queryset links to maintian multiple filters.

get_queryset()[source]
Performs the following steps:
  • Returns the queryset if the form is invalid.
  • Otherwise, filters the queryset based on the filters defined on the form.
  • Returns the filtered queryset.
post_filter(qs)[source]

Hook for doing post-filter modification to the queryset. This is also the place where any custom filtering should take place.

Runs only if the form validates.

pre_filter(qs)[source]

Hook for doing pre-filter modification to the queryset

Runs prior to any form filtering and is run regardless form validation.

class fusionbox.forms.SortForm(*args, **kwargs)[source]

Base class for implementing sorting on a model.

# Example Usage

class UserSortForm(SortForm):
    HEADERS = (
        {'column': 'username', 'title': 'Username', 'sortable': True},
        {'column': 'email', 'title': 'Email Address', 'sortable': True},
        {'column': 'is_active', 'title': 'Active', 'sortable': False},
    model = User

The sort field for this form defaults to a HiddenInput widget which should be output within your form to preserve sorting accross any form submissions.

get_queryset()[source]

Returns an ordered queryset, sorted based on the values submitted in the sort parameter.

headers()[source]

Returns an object with the following template variables:

{{ form.headers }}
  • access to the header
{{ header.title }}
  • title declared for this header
{{ header.sortable }}
  • boolean for whether this header is sortable
{{ header.active }}
  • boolean for whether the queryset is currently being sorted by this header
{{ header.classes }}
  • list of css classes for this header. (active, ascending|descending)
{{ header.priority }}
  • numeric index for which place this header is being used for ordering.
{{ header.querystring }}
  • querystring for use with progressive sorting (sorting by multiple fields)
{{ header.remove }}
  • querystring which can be used to remove this header from sorting
{{ header.singular }}
  • querystring which can be used to sort only by this header

Example:

{% for header in form.headers %}
  {% if header.priority %}
  <th scope="col" class="active {{ form.prefix }}-{{ header.column }}">
    <div class="sortoptions {{ header.classes|join:' ' }}">
      <a class="sortremove" href="?{{ header.remove }}" title="Remove from sorting">X</a>
      <span class="sortpriority" title="Sorting priority: {{ header.priority }}">{{ header.priority }}</span>
      <a href="?{{ header.querystring }}" class="toggle" title="Toggle sorting"></a>
    </div>
  {% else %}
  <th scope="col" class="{{ form.prefix }}-{{ header.column }}">
  {% endif %}

  {% if header.sortable %}
     <div class="text"><a href="?{{ header.querystring }}">{{ header.title }}</a></div>
  {% else %}
     <div class="text">{{ header.title|safe }}</div>
  {% endif %}
  </th>
{% endfor %}
post_sort(qs)[source]

Hook for doing post-sort modification of the queryset. Will not be called on an invalid form.

pre_sort(qs)[source]

Hook for doing pre-sort modification of the queryset. Runs regardless of whether the form is valid.

class fusionbox.forms.CsvForm(*args, **kwargs)[source]

Base class for implementing csv generation on a model.

Example:

# Given this class...

class UserFilterForm(FilterForm):
    model = User

    CSV_COLUMNS = (
            {'column': 'id', 'title': 'Id'},
            {'column': 'username', 'title': 'Username'},
            {'column': 'email__domain_name', 'title': 'Email Domain'},
            )

    FILTERS = {
        'active': 'is_active',
        'date_joined': 'date_joined__gte',
        'published': None, # Custom filtering
        }

    PUBLISHED_CHOICES = (
            ('', 'All'),
            ('before', 'Before Today'),
            ('after', 'After Today'),
            )

    active = forms.BooleanField(required=False)
    date_joined = forms.DateTimeField(required=False)
    published = forms.ChoiceField(choices=PUBLISHED_CHOICES, widget=forms.HiddenInput())

    def pre_filter(self, queryset):
        published = self.cleaned_data.get('published')
        if published == '':
            return queryset
        elif published == 'before':
            return queryset.filter(published_at__lte=datetime.datetime.now())
        elif published == 'after':
            return queryset.filter(published_at__gte=datetime.datetime.now())
>>> # This code in a repl will produce a string buffer with csv output for
>>> # the form's queryset
>>> form = UserFilterForm(request.GET, queryset=User.objects.all())
>>> form.csv_content()
<StringIO.StringO object at 0x102fd2f48>
>>>

CSV_COLUMNS defines a list of properties to fetch from each obj in the queryset which will be output in the csv content. The column key defines the lookup path for the property. This can lookup a field, property method, or method on the model which may span relationships. The title key defines the column header to use for that property in the csv content.

The csv_content() method returns a string buffer with csv content for the form’s queryset.

csv_content()[source]

Returns the objects in the form’s current queryset as csv content.

class fusionbox.forms.UncaptchaForm(data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=<class 'django.forms.util.ErrorList'>, label_suffix=':', empty_permitted=False)[source]

Extension of django.forms.Form which adds an UncaptchaField to the form.

class fusionbox.forms.UncaptchaModelForm(data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=<class 'django.forms.util.ErrorList'>, label_suffix=':', empty_permitted=False, instance=None)[source]

Extension of django.forms.ModelForm which adds an UncaptchaField to the form.

fusionbox.forms.csv_getattr(obj, attr_name)[source]

Helper function for CsvForm class that gets an attribute from a model with a custom exception.

Fields

class fusionbox.forms.MonthField(*args, **kwargs)[source]

MonthField is a TypedChoiceField that selects a month. Its python value is a 1-indexed month number.

class fusionbox.forms.MultiFileField(*args, **kwargs)[source]

Implements a multifile field for multiple file uploads.

This class’ clean method is implented by currying super.clean and running map over data which is a list of file upload objects received from the MultiFileWidget.

Using this field requires a little work on the programmer’s part in order to use correctly. Like other Forms with fields that inherit from FileField, the programmer must pass in the kwarg files when creating the form instance. For example:

` form = MyFormWithFileField(data=request.POST, files=request.FILES) `

After validation, the cleaned data will be a list of files. You might want to iterate over in a manner similar to this:

``` if form.is_valid():

for media_file in form.cleaned_data[‘field_name’]:
MyMedia.objects.create(
name=media_file.name, file=media_file )

```

widget

alias of MultiFileWidget

class fusionbox.forms.NoAutocompleteCharField(max_length=None, min_length=None, *args, **kwargs)[source]

NoAutocompleteCharField is a subclass of CharField that sets the autocomplete attribute to off. This is suitable for credit card numbers and other such sensitive information.

This should be used in conjunction with the sensitive_post_parameters <https://docs.djangoproject.com/en/dev/howto/error-reporting/#sensitive_post_parameters> decorator.

class fusionbox.forms.fields.FutureYearField(number_of_years=6, *args, **kwargs)[source]

FutureYearField is a TypedChoiceField that selects a year a defined period in the future. Useful for credit card expiration dates.