我已经坚持了一天多,希望能得到一些帮助。我已经阅读了许多关于表单、表单集、绑定和未绑定表单的不同 SO 帖子和Django
文档,但仍然无法弄清楚这一点。
我正在从一个模型中提取一些数据,该模型是JSONField
. 这是一个嵌套的字典(dict),如下所示:
dict= {
'A':'data1',
'B': [ {
'one': [
{'x': 'data2', 'y': 'data3', 'z': 'data4'},
{'x': 'data5', 'y': 'data6', 'z': 'data7'},
{'x': 'data8', 'y': 'data9', 'z': 'data10'}
],
'two':'val',
'three': {
'color':'red',
'size':'big',
'order':'new'
},
'four':'someVal',
}],
'C':'moreData'
}
内部列表one将在其中包含动态数量的字典,在此示例中,只有 3 个。one的键将始终相同(x、y 和 z),但值会改变。
我需要创建一个可编辑的表单,它的每个键都在它自己的字符字段中,初始数据集作为值。
我已经查看并尝试了一些软件包(django-entangled
, django-json-widget
, django-SplitJSONWidget-form
..),但没有任何运气。
我已经尝试过绑定和未绑定的形式。我得到的壁橱采用了这种方法:
# MODEL:
class myModel(models.Model):
foo = JSONField(blank=True)
# ===========================================================
# FORM:
class oneForm(forms.Form):
A = CharField()
B = CharField()
C = CharField()
class twoForm(forms.Form)
two = CharField()
four = CharField()
# for one(list):
class triForm(forms.Form):
x = charField()
y = charField()
z = charField()
# for three(nested-dict):
class fourForm(forms.Form):
color = CharField()
size = CharField()
order = CharField()
# ===========================================================
# VIEW:
def myView(request,pk):
# getting value of model.Field(JSONField)
obj = myModel.objects.get(pk=pk)
myJson = getattr(obj,'foo')
# Get count of list(one) because it'll dynamically change (this example = 3)
list_count = len(myJson['B'][0]['one'])
# Dynamically populate lines:
one_list = [myJson['B'][0]['one'][i] for i in range(list_count)]
if request.method == "POST":
form = oneForm(initial=myJson) # for first level of dict.
form2 = twoForm(initial=myJson['B'][0]) # for second level of list.
form3 = triForm(initial=one_list) # for one list
form4 = fourForm(initial=myJson['B'][0]['three']) # for three dict.
if form.is_valid():
data = form.save(commit=False)
# Haven't even got around to try and reformat all the data and save it...
data.save()
return HttpResponseRedirect(reverse('blah:home', args=(pk,)))
else:
form = oneForm(initial=myJson) # for first level of dict.
form2 = twoForm(initial=myJson['B'][0]) # for second level of list.
form3 = triForm(initial=one_list) # for one list
form4 = fourForm(initial=myJson['B'][0]['three']) # for three dict.
return render(request, T, {
'form': form,
'form2': form2,
'form3': form3,
'form4': form4,
'range': range(list_count),
})
# ===========================================================
# TEMPLATE:
... some html / form tags
{{ form.as_p }}
{{ form2.as_p }}
{{ form3.as_p }}
{{ form4.as_p }}
... closing tags
这条路线为我提供了正确的数据字段和初始输入,尽管它不会动态填充内部列表(一个)。它只会显示第一个字典。
x [ 数据 2 ]
y [ 数据 3 ]
z [ 数据 4 ]
...我尝试通过 {% for x in range %} 运行它,但它只会重新打印上述 3 次而不会获得不同的值(数据 5、6、7、8、9、10)。
任何信息或提示都会有所帮助!