1

I would like to use django forms to validate fields being Integer Array. What is the best way to achieve this ? I don't want to use a ChoiceField and I am not sure what is the easiest way to achieve this. Any suggestion in that matter ?

1 Answer 1

2

For storing the array I would use a django-picklefield or a custom field like this:

from django.db import models

class IntArrayField(models.TextField):
    __metaclass__ = models.SubfieldBase

    def __init__(self, *args, **kwargs):
        super(IntArrayField, self).__init__(*args, **kwargs)

    def to_python(self, value):
        if not value: 
            return None
        if isinstance(value, list):
            return value
        return [int(n) for n in value.split('|')]

    def get_db_prep_value(self, value):
        if not value: 
            return None
        assert(isinstance(value, list) or isinstance(value, tuple))
        return '|'.join(str(value))

    def value_to_string(self, obj):
        value = self._get_val_from_obj(obj)
        return self.get_db_prep_value(value)

For validation you can use clean_fieldname():

def clean_fieldname(self):
        data = self.cleaned_data['fieldname']
        # if <data is not an int array>:
        #    raise forms.ValidationError("You must enter an int array.")

        return data

And it's also good to have some JavaScript code to validate input and make entering an int array easier on your client side.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.