Login

SeparatedValuesField

Author:
jezdez
Posted:
December 5, 2007
Language:
Python
Version:
.96
Tags:
newforms field comma separated
Score:
4 (after 4 ratings)

A Django newforms field which takes another newforms field during initialization and validates every item in a comma-separated list with this field class. Please use it like this:

from django.newforms import EmailField
emails = CommaSeparatedValuesField(EmailField)

You would be able to enter a string like "john@doe.com,guido@python.org" because every email address would be validated when clean() is executed. This of course also applies to any other Field class.

You can define the sepator (default: ",") during initialization with the separator parameter like this:

from django.newforms import EmailField`
emails = SeparatedValuesField(EmailField, separator="###")
 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
from django import newforms as forms

class SeparatedValuesField(forms.Field):
    """
    A Django newforms field which takes another newforms field during
    initialization and validates every item in a separated list with
    this field class. Please use it like this::
    
        from django.newforms import EmailField
        emails = SeparatedValuesField(EmailField)
    
    You would be able to enter a string like "john@doe.com,guido@python.org"
    because every email address would be validated when clean() is executed.
    This of course also applies to any other Field class.
    
    You can define the sepator (default: ",") during initialization with the
    ``separator`` parameter like this::
    
        from django.newforms import EmailField
        emails = SeparatedValuesField(EmailField, separator="###")
    
    If validation succeeds it returns the original data, though the already
    splitted value list can be accessed with the get_list() method.
    
    >>> f = SeparatedValuesField(forms.EmailField)
    >>> f.clean("foo@bar.com,bar@foo.com")
    'foo@bar.com,bar@foo.com'
    >>> f.get_list()
    ['foo@bar.com', 'bar@foo.com']
    >>> f.clean("foobar,foo@bar.com,bar@foo.com")
    Traceback (most recent call last):
        ...
    ValidationError: <unprintable ValidationError object>
    >>> u = SeparatedValuesField(forms.URLField)
    >>> u.clean("http://foo.bar.com,http://foobar.com")
    'http://foo.bar.com,http://foobar.com'
    >>> u.clean("http:foo.bar.com")
    Traceback (most recent call last):
        ...
    ValidationError: <unprintable ValidationError object>
    >>> f = SeparatedValuesField(forms.EmailField, separator="###")
    >>> f.clean("foo@bar.com###bar@foo.com")
    'foo@bar.com###bar@foo.com'
    >>> f.clean("foobar###foo@bar.com###bar@foo.com")
    Traceback (most recent call last):
        ...
    ValidationError: <unprintable ValidationError object>
    
    """
    def __init__(self, base_field=None, separator=",", *args, **kwargs):
        super(SeparatedValuesField, self).__init__(*args, **kwargs)
        self.base_field = base_field
        self.separator = separator

    def clean(self, data):
        if not data:
            raise forms.ValidationError('Enter at least one value.')
        self.value_list = data.split(self.separator)
        if self.base_field is not None:
            base_field = self.base_field()
            for value in self.value_list:
                base_field.clean(value)
        return data
    
    def get_list(self):
        return self.value_list

def _test():
    import doctest
    doctest.testmod()

if __name__ == "__main__":
    _test()

More like this

  1. Multiple emails form field by matrix 1 year, 2 months ago
  2. Multiple emails field by cuchac 10 months ago
  3. MultipleEmailsField by spanasik 5 years, 10 months ago
  4. Newforms field for decimals with a comma by jonasvp 6 years, 11 months ago
  5. MultipleChoiceCommaField by rubic 8 years ago

Comments

lukas (on March 9, 2008):

This is pretty cool, thanks! But it doesn't work if the form field (ie EmailField) is allowed to be empty :(

#

lukas (on March 9, 2008):

This fixes it and also adds a 'strip' field so that you can ignore whitespace in the input:

    def __init__(self, base_field=None, separator=",", strip=False, *args, **kwargs):
        super(SeparatedValuesField, self).__init__(*args, **kwargs)
        self.base_field = base_field
        self.separator = separator
        self.strip = strip

    def clean(self, data):
        if not data:
            if self.required:
                raise forms.ValidationError('Enter at least one value.')
            else:
                return None
        self.value_list = data.split(self.separator)
        if self.base_field is not None:
            base_field = self.base_field()
            for value in self.value_list:
                if self.strip:
                    value = value.strip()

                base_field.clean(value)
        return data

#

Please login first before commenting.