You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django分页字典值时出现unhashable type: 'slice'错误求助

解决Django字典数据分页的"unhashable type: 'slice'"错误

错误原因

  1. Django Paginator不支持直接分页字典:Paginator要求传入的对象是可切片的序列(如列表、QuerySet),而字典本身不支持切片操作,直接传入字典会触发unhashable type: 'slice'错误。
  2. 分页逻辑位置错误:你把分页代码写在了遍历城市的for循环内部,每次循环都会重新创建Paginator,这不仅无效,还会导致逻辑混乱。

修复方案

将字典转换为可迭代的列表结构(比如字典的键值对列表),并把分页逻辑移到所有数据收集完成之后。

修改后的views.py代码

from django.shortcuts import render
import urllib.request
import json
from django.core.paginator import Paginator

def display(request):
    cities=['vijayawada','guntur','tenali','rajahmundry','amaravathi','Bengaluru','Mangaluru','Chikkamagaluru','Chennai']
    data = {}
    for city in cities:
        # 添加异常处理,避免API请求失败导致程序崩溃
        try:
            source = urllib.request.urlopen(
                'https://api.openweathermap.org/data/2.5/weather?q=' + city + '&units=metric&appid=APIID').read()
            list_of_data = json.loads(source)

            data[city] = {
                "country_code": str(list_of_data['sys']['country']),
                "coordinates": {
                    'latitude':  str(list_of_data['coord']['lat']),
                    'longitude': str(list_of_data['coord']['lon'])
                },
                "temp": str(list_of_data['main']['temp']) + ' °C',
                "pressure": str(list_of_data['main']['pressure']),
                "humidity": str(list_of_data['main']['humidity']),
                'main': str(list_of_data['weather'][0]['main']),
                'description': str(list_of_data['weather'][0]['description']),
                'icon': list_of_data['weather'][0]['icon'],
            }
        except Exception as e:
            print(f"获取{city}天气数据失败: {e}")
            continue

    # 将字典转换为键值对列表,用于分页
    data_list = list(data.items())
    # 初始化分页器,每页3条数据
    p = Paginator(data_list, 3)
    page = request.GET.get('page')
    # 获取当前页的数据
    paginated_data = p.get_page(page)

    context = {'data': paginated_data}
    return render(request, 'display.html', context)

模板display.html示例

在模板中遍历分页数据时,每个元素是(城市名, 天气数据)的元组,可按如下方式解包使用:

<!DOCTYPE html>
<html>
<head>
    <title>天气数据分页展示</title>
</head>
<body>
    {% for city_name, city_info in data %}
        <div class="weather-card">
            <h3>{{ city_name }}</h3>
            <p>国家代码: {{ city_info.country_code }}</p>
            <p>温度: {{ city_info.temp }}</p>
            <p>湿度: {{ city_info.humidity }}</p>
            <p>天气状况: {{ city_info.main }} - {{ city_info.description }}</p>
            <img src="http://openweathermap.org/img/w/{{ city_info.icon }}.png" alt="天气图标">
        </div>
    {% endfor %}

    <!-- 分页导航 -->
    <div class="pagination">
        {% if data.has_previous %}
            <a href="?page={{ data.previous_page_number }}">上一页</a>
        {% endif %}
        <span>第 {{ data.number }} 页 / 共 {{ data.paginator.num_pages }} 页</span>
        {% if data.has_next %}
            <a href="?page={{ data.next_page_number }}">下一页</a>
        {% endif %}
    </div>
</body>
</html>

内容的提问来源于stack exchange,提问作者Vidya L

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 08:01:21