问题
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, foobar]
bb: {'some map values'}
}
bar: [str!! "", str!! ""]
foobar: [str!! "", str!! ""]
...
My goal is a web interface which allows to create/modify/save and display such data. I can't imagine how to define a form and a model for such kind of data. The problem is that the data is not static, for example the user can add as many list items as he wants for 'ff' value, i.e. it is not fixed two items 'bar' and 'foobar', there may be unlimited number of items added. (The same for the rest of sequenced data). I only know that the value for 'ff' is a list value. (I imagine the web view with some small "+" sign allowing to add data.)
As soon as the form is filled I want to be able to use pyyaml to convert it to yaml and save the data. And the reverse - load the data from a file and display in the form to allow modifications.
So in two words - how to deal with "dynamic, sequenced form/model fields".
P.S. Another problem I have here is having not built-in type fields. I think of having a separate form for each that kind of field and "reference" with Foreign Key. Is that a right way to go? Or may be going with defining custom fields is better?
Many thanks in advance!!
回答1:
If you don't want to create concrete Models for your lists you could use django-picklefield:
from picklefield.fields import PickledObjectField
class MyModel(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:
class MyModelForm(forms.ModelForm):
class Meta:
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))
def clean_my_list(self):
data = self.cleaned_data.get('my_list', '')
if data:
return data.split(",") # Add error check, convert to number, etc
return []
来源:https://stackoverflow.com/questions/27602294/django-want-to-have-a-form-for-dynamically-changed-sequence-data