努力在模板中解开二维列表

时间:2019-02-01 10:36:22

标签: python django django-templates django-views

我正在将大量数据传递到模板中,但是很难拆分出压缩的项目列表。无论我尝试什么,我总是会遇到以下错误。

  

需要2个值才能解开for循环;得到0。

这里是我的代码:

views.py

import requests
from django.shortcuts import render
from django.http import HttpResponse

dictionary, words = [[], []], []


def home(request, username='johnny'):
    template_name = 'main/index.html'
    url = "https://www.duolingo.com/users/{}".format(username)
    getUserData(url)
    context = {
        'username': username,
        'dictionary': dictionary,
        'words': words,
    }
    # print(context)
    return render(request, template_name, context)


def getUserData(url):
    response = requests.get(url)
    userdata = response.json()
    wordlists, explanations = [], []

    for language in userdata['language_data']:
        for index in userdata['language_data'][language]['skills']:
            if index.get('levels_finished') > 0:
                wordList = index.get("words")
                wordlists.append(wordList)
                explanations.append(index.get("explanation"))
                for wordItem in wordList:
                    words.append(wordItem)
    dictionary = list(zip(wordlists, explanations))

相关模板

{% block content %}
    {% for words, exp in dictionary %}
      {{ words }}
      {{ exp|safe }}
    {% endfor %}
{% endblock %}

我已经测试了此代码,它可以工作。

enter image description here

一旦我在Django中进行了重构,将wordLists放入带有解释的数组中,事情就死了。如果我在方法末尾print(dictionary),则数据将显示在控制台中。不知道我还缺少什么。

1 个答案:

答案 0 :(得分:2)

您的问题出在scope上。您从home函数(作为上下文)返回的字典(变量)和getUserData函数中的字典不在同一范围内。因此,无论何时更新getUserData方法的字典,都不会在home中对其进行更新。我不建议您将字典的方法设为its using global variable。我会推荐这样的东西:

def getUserData(url):
    response = requests.get(url)
    userdata = response.json()
    wordlists, explanations, words = [], [], []

    for language in userdata['language_data']:
        for index in userdata['language_data'][language]['skills']:
            if index.get('levels_finished') > 0:
                wordList = index.get("words")
                wordlists.append(wordList)
                explanations.append(index.get("explanation"))
                for wordItem in wordList:
                    words.append(wordItem)
    return list(zip(wordlists, explanations)), words  # return the value of dictionary from here


def home(request, username='johnny'):
    template_name = 'main/index.html'
    url = "https://www.duolingo.com/users/{}".format(username)
    dictionary, words = getUserData(url)  # catch value of dictionary
    context = {
        'username': username,
        'dictionary': dictionary,
        'words': words,
    }
    # print(context)
    return render(request, template_name, context)