Login

SeparatedValuesField

Author:
jezdez
Posted:
December 5, 2007
Language:
Python
Version:
.96
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 "[email protected],[email protected]" 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 "[email protected],[email protected]"
    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("[email protected],[email protected]")
    '[email protected],[email protected]'
    >>> f.get_list()
    ['[email protected]', '[email protected]']
    >>> f.clean("foobar,[email protected],[email protected]")
    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("[email protected]###[email protected]")
    '[email protected]###[email protected]'
    >>> f.clean("foobar###[email protected]###[email protected]")
    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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 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

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.