Forms Module¶
Forms¶
-
class
fusionbox.forms.
BaseChangeListForm
(*args, **kwargs)[source]¶ Base class for all
ChangeListForms
.
-
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
toTrue
to make searches case sensitive.-
get_queryset
()[source]¶ Constructs an ‘__contains’ or ‘__icontains’ filter across all of the fields listed in
SEARCH_FIELDS
.
-
-
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.
-
-
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 %}
-
-
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. Thecolumn
key defines the lookup path for the property. This can lookup a field, property method, or method on the model which may span relationships. Thetitle
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.
-
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.
Fields¶
-
class
fusionbox.forms.
MonthField
(*args, **kwargs)[source]¶ MonthField
is aTypedChoiceField
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:
-
widget
¶ alias of
MultiFileWidget
-
-
class
fusionbox.forms.
NoAutocompleteCharField
(max_length=None, min_length=None, *args, **kwargs)[source]¶ NoAutocompleteCharField
is a subclass ofCharField
that sets theautocomplete
attribute tooff
. 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.