Задать вопрос

Тел: +7 965 3737 888

491

Просмотров

2

Ответов

SeparatedValuesField

<p>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:</p>
from django.newforms import EmailField
emails = CommaSeparatedValuesField(EmailField)

<p>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.</p>
<p>You can define the sepator (default: ",") during initialization with the
separator parameter like this:</p>
from django.newforms import EmailField`
emails = SeparatedValuesField(EmailField, separator="###")

Вопрос полезен? Да0/Нет0
file_2981.py(2.7Кб)
None

Ответы (2):

Ответlukas:09.03.2008
Ответ полезен? Да0/Нет0

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

Ответlukas:09.03.2008
Ответ полезен? Да0/Нет0

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