Login

RangeField and RangeWidget

Author:
marinho
Posted:
October 2, 2008
Language:
Python
Version:
1.0
Score:
0 (after 2 ratings)

These field and widget are util for to those fields where you can put a star and end values.

It supports most of field types and widgets (tested with IntegerField, CharField and DateField / TextInput and a customized DateInput).

Example of use:

class FormSearch(forms.Form):
    q = forms.CharField(max_length=50, label=_('Search for'))
    price_range = RangeField(forms.IntegerField, required=False)

Example of use (with forced widget):

class FormSearch(forms.Form):
    q = forms.CharField(max_length=50, label=_('Search for'))
    price_range = RangeField(forms.IntegerField, widget=MyWidget)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
from django import forms
from django.template.loader import render_to_string
from django.forms.fields import EMPTY_VALUES
from django.utils.translation import ugettext as _

class RangeWidget(forms.MultiWidget):
    def __init__(self, widget, *args, **kwargs):
        widgets = (widget, widget)

        super(RangeWidget, self).__init__(widgets=widgets, *args, **kwargs)

    def decompress(self, value):
        return value

    def format_output(self, rendered_widgets):
        widget_context = {'min': rendered_widgets[0], 'max': rendered_widgets[1],}
        return render_to_string('widgets/range_widget.html', widget_context)

class RangeField(forms.MultiValueField):
    default_error_messages = {
        'invalid_start': _(u'Enter a valid start value.'),
        'invalid_end': _(u'Enter a valid end value.'),
    }

    def __init__(self, field_class, widget=forms.TextInput, *args, **kwargs):
        if not 'initial' in kwargs:
            kwargs['initial'] = ['','']

        fields = (field_class(), field_class())

        super(RangeField, self).__init__(
                fields=fields,
                widget=RangeWidget(widget),
                *args, **kwargs
                )

    def compress(self, data_list):
        if data_list:
            return [self.fields[0].clean(data_list[0]),self.fields[1].clean(data_list[1])]

        return None

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

jjudge (on August 9, 2009):

Can we get an example of a 'widgets/range_widget.html'??

#

Haikson (on July 9, 2017):

'widgets/range_widget.html'

<div> <label>From: {{ min }}</label> <label>To {{ max }}</label> </div>

#

Please login first before commenting.