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

模板<select>传递字典至视图报错:string indices must be integers

解决"string indices must be integers"错误的方案

错误原因分析

你遇到的问题核心在于:<option>的value属性最终渲染后是字符串格式的字典(比如"{'Game':3,'Platforme':3}"),而不是Python中的真实字典对象。当你通过request.POST['game']获取到的是这个字符串,尝试用post['game']['Game']去索引时,Python会把它当成普通字符串,自然报错"string indices must be integers"——因为字符串只能用数字索引位置,不能用键名。


解决方案

这里提供两种靠谱的处理方式,你可以根据需求选择:

方式1:用JSON格式传递并解析

这是更规范的做法,避免字符串解析的潜在问题:

  1. 模板层修改:把字典转成标准JSON字符串(注意JSON要求键用双引号)

    <option value='{"Game":{{ game.on_game.id }},"Platforme":{{ game.on_plateform.id }}}'>
    
  2. 视图层解析:把获取到的字符串转成Python字典

    import json
    from django.http import HttpResponseBadRequest
    
    post = request.POST
    try:
        game_data = json.loads(post['game'])
    except json.JSONDecodeError:
        return HttpResponseBadRequest("Invalid game data")
    
    entry = InboxRecruiting()
    try:
        entry.on_game = Games.objects.get(id=game_data['Game'])
        entry.on_platforme = Plateform.objects.get(id=game_data['Platforme'])
        entry.save()
    except (Games.DoesNotExist, Plateform.DoesNotExist):
        return HttpResponseBadRequest("Invalid game or platform ID")
    

方式2:用分隔符拼接值(更简单直接)

如果不想用JSON,也可以用特定分隔符把两个ID拼在一起:

  1. 模板层修改:

    <option value="{{ game.on_game.id }}|{{ game.on_plateform.id }}">
    

    这里用|作为分隔符,只要这个字符不会出现在ID里就行,也可以用逗号、短横线等。

  2. 视图层拆分:

    from django.http import HttpResponseBadRequest
    
    post = request.POST
    game_platform_ids = post['game'].split('|')
    if len(game_platform_ids) != 2:
        return HttpResponseBadRequest("Invalid game data")
    
    game_id, platform_id = game_platform_ids
    entry = InboxRecruiting()
    try:
        entry.on_game = Games.objects.get(id=game_id)
        entry.on_platforme = Plateform.objects.get(id=platform_id)
        entry.save()
    except (Games.DoesNotExist, Plateform.DoesNotExist):
        return HttpResponseBadRequest("Invalid game or platform ID")
    

额外建议

  • 一定要加上异常处理:比如处理ID无效导致的模型不存在错误,避免程序崩溃。
  • 如果是Django项目,推荐使用ModelForm来处理数据验证和保存,代码会更简洁安全。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:10:40