Skip to content Skip to sidebar Skip to footer

Django: Want To Have A Form For Dynamically Changed Sequence Data

Django experts - I am a newbie and need your help with the following. Suppose I have some complicated data structure, an arbitrary example: (yaml format) foo: { ff: [ bar, foo

Solution 1:

If you don't want to create concrete Models for your lists you could use django-picklefield:

from picklefield.fields import PickledObjectField

classMyModel(models.Model):
    my_list =PickledObjectField(default=[])

Then use it like this:

m1 = MyModel()
m1.my_list = [1, 2, 3]
m1.save()
m2 = MyModel()
m2.my_list = ["a", "b", "c", "d"]
m2.save()

UPDATE

In forms you should create custom fields based on the type of data you need. The simplest is to use a text field and convert the comma seperated text into a list:

classMyModelForm(forms.ModelForm):classMeta:
        model = MyModel

    def__init__(self, *args, **kwargs):
        super(MyModel, self).__init__(*args, **kwargs)
        self.fields["my_list"] = forms.CharField(initial=",".join(self.instance.my_list))

    defclean_my_list(self):
        data = self.cleaned_data.get('my_list', '')
        ifdata:return data.split(",") # Add error check, convert to number, etcreturn []

Post a Comment for "Django: Want To Have A Form For Dynamically Changed Sequence Data"