簡體   English   中英

努力在模板中解壓縮二維列表

[英]Struggles unpacking a two-dimensional list in template

我正在將大量數據傳遞到模板中,但是很難拆分項目的壓縮列表。 無論我嘗試什么,我總是會遇到以下錯誤。

需要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 %}

我已經測試了此代碼,它可以工作。

在此處輸入圖片說明

一旦我在Django中進行了重構,將wordLists放入帶有解釋的數組中,事情就死了。 如果在方法末尾print(dictionary) ,則數據將顯示在控制台中。 不知道我還缺少什么。

您的問題是范圍 home函數(作為上下文)返回的字典(變量)和getUserData函數中的字典不在同一范圍內。 因此,無論何時更新getUserData方法的字典,都不會在home對其進行更新。 我不建議您使用字典方法,因為它使用全局變量 我建議這樣的事情:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM