views:

52

answers:

1

I want to store a variable-length list of floats in Django. There is the CommaSeparatedIntegerField, but is there anything like this that I could use? Would it be best to just implement my own CommaSeparetedFloatField or is there something that I am missing completely? Thanks.

+3  A: 

I think you can define your own field quite easily:

comma_separated_float_list_re = re.compile('^([-+]?\d*\.?\d+[,\s]*)+$')
validate_comma_separated_float_list = RegexValidator(
              comma_separated_float_list_re, 
              _(u'Enter only floats separated by commas.'), 'invalid')

class CommaSeparatedFloatField(CharField):
    default_validators = [validators.validate_comma_separated_float_list]
    description = _("Comma-separated floats")

    def formfield(self, **kwargs):
        defaults = {
            'error_messages': {
                'invalid': _(u'Enter only floats separated by commas.'),
            }
        }
        defaults.update(kwargs)
        return super(CommaSeparatedFloatField, self).formfield(**defaults)

This snippet is not testet but maybe you can adapt it for your needs.

aeby