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

Django加密更新URL ID遇'int不可迭代'错误求助

Django加密用户ID修复方案

问题分析

  1. 'int object is not iterable'错误:request.user.id是整数类型,无法直接用于for循环遍历。
  2. 多编辑链接问题:模板中循环遍历列表导致生成多个编辑按钮,实际仅需显示当前用户的编辑链接。

修复后的代码

个人资料页视图代码

def profile(request):
    # 直接处理当前登录用户,无需循环
    user_data = {
        'id': request.user.id,
        'encrypt_key': encrypt(request.user.id)
    }
    return render(request, 'profile.html', {'user_data': user_data})

HTML模板代码

<li class="ctx-item">
  <button class="ctx-menu-btn icon-box">
      <span class="material-symbols-rounded  icon" aria-hidden="true">edit</span>
      <span class="ctx-menu-text">
          <a href="/update/{{ user_data.encrypt_key }}">Edit</a>
      </span>
  </button>
</li>

更新视图代码(保留原逻辑即可)

def update(request, id):
    id = decrypt(id)
    # 此处添加更新逻辑
    return render(request, 'edit_profile.html', context)

修复说明

  • 视图中直接获取当前登录用户的ID,生成加密key后封装成单个字典传递给模板,彻底避免遍历整数的错误。
  • 模板中移除循环逻辑,直接使用单个用户的加密key生成编辑链接,确保仅显示一个符合当前用户的编辑按钮。

内容的提问来源于stack exchange,提问作者TS Tamarai Selvan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 00:40:44