我怎样才能获得以下集合并在其中迭代它 django模板?
[('Foo Key', [{'lname': 'Bar', 'fname': 'Foo'}])]
请注意,上面的示例要小得多,只是为了简单起见。 如果我们需要完全扩展的集合,例如,如果大小很重要,我可以更新这篇文章。
我最近的成功尝试如下所述。
{% for key0, value0 in data %}
<tr>
<td> key0 {{ key0 }}:</td>
<td> value0 {{ value0 }} </td>
</tr>
<p> {% for value1 in value0 %}
<td> {{ value1 }}</td>
{% endfor %}
</p>
{% endfor %}
这将使我得到以下输出。
Foo Key {&#39; lname&#39;:&#39; Bar&#39;,&#39; fname&#39;:&#39; Foo&#39;}
我似乎无法得到&#39; Bar&#39;或者&#39; Foo&#39;出来的。
其他一些背景 以下是生成数据的视图
from django.shortcuts import render
from .models import Person, PersonMeta
# Create your views here.
def thanks(request):
return render(request, 'thanks.html')
from .forms import NameForm
def home(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
# check whether it's valid:
if form.is_valid():
data = {}
# process the data in form.cleaned_data as required
currentUser = request.user
person = Person.objects.create(first_name=currentUser.first_name, last_name=currentUser.last_name,
nickname=form.cleaned_data['nickname'])
# getting front loaded personMeta
personDetails = PersonMeta.objects.filter(frontLoaded_first_name=currentUser.first_name,frontLoaded_last_name=currentUser.last_name).values()
# setting key
currUserKey = "{0} {1}".format(currentUser.first_name, currentUser.last_name)
# if person details is not false
# this if may not have to be here.
if (personDetails):
data[currUserKey] = personDetails
# redirect to a new URL:
return render(request, 'signUp.html', {'data': sorted(data.items())})
# if a GET (or any other method) we'll create a blank form
#
else:
form = NameForm()
return render(request, 'home.html', {'form': form})
答案 0 :(得分:1)
dict
中有一个list
,这是另一个tuple
内list
的第二个值:
[('Foo Key', [{'lname': 'Bar', 'fname': 'Foo'}])]
所以我们走了:
{% for tuple in data %}
<p>Tuple key: {{ tuple.0 }}</p>
{% for key, value in tuple.1.0.items %}
<p>Dict key, value: {{ key }}: {{ value }}</p>
{% endfor %}
{% endfor %}