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

Django报错:Field 'id'期望数值却获取到'None',求助解决

报错求助:ValueError at /state/ Field 'id' expected a number but got 'None'

遇到以下错误,尝试将值转为整数后仍无法解决,卡了30分钟找不到问题所在,求帮忙:

ValueError at /state/ Field 'id' expected a number but got 'None'

相关代码

urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', cview.Insertrecord),
    path('country/', lview.Insertrecord),
    path('state/', lview.Insertrecord_state),
]

models.py

class customer_state(models.Model):
    parent_id=models.ForeignKey(customer_location, on_delete=models.CASCADE)
    name=models.CharField(max_length=100)
    status=models.CharField(max_length=100, default='nil')
    added_by=models.CharField(max_length=100, default=1)
    updated_by=models.CharField(max_length=100, default=1)
    created_on=models.CharField(max_length=100)
    updated_on=models.CharField(max_length=100)
    class Meta:
        db_table="customer_state"

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        self.created_on = get_current_datetime_str()
        self.updated_on = get_current_datetime_str()
        super().save(*args, **kwargs)

views.py

def Insertrecord_state(request):
    # Define the parent_id variable
    parent_id = None
    
    if request.method=='POST':
        if request.POST.get('parent_id')...... and request.POST.get('updated_on'):
           
            parent_id = request.POST.get('parent_id')
            
            parent_location = customer_location.objects.get(id=parent_id)
            
            saverecord=customer_state()
            saverecord.parent_id=parent_location
            saverecord.name=request.POST.get('name')
            
            saverecord.save()
            messages.success(request,"Record Saved Successfully..!")
            return render(request, 'state.html', {'parent_id': parent_id})
    else:
        # Return the form with the parent_id variable
        return render(request,'state.html', {'parent_id': parent_id})

state.html

<div class="container-sm">
      <form method = "POST">
        {% csrf_token %}
        <div class="row mb-3" style="display:none">
          <label for="inputEmail3" class="col-sm-2 col-form-label">Parent ID</label>
          <div class="col-sm-10">
            <input type="text" value="{{ parent_id }}" name="parent_id" class="form-control" id="inputEmail3" required/>
          </div>
        </div>
         .
         .
</form>

错误截图

错误截图

问题分析与解决方案

核心原因

  1. GET请求时parent_id默认设为None:直接访问/state/时,parent_id被初始化为None,模板中input的value会被渲染成字符串'None'(或空值),提交表单时POST的parent_id不是有效数字,导致执行customer_location.objects.get(id=parent_id)时,数据库期望数字类型的id,但收到了None或无效字符串。
  2. POST参数校验不严谨:代码中request.POST.get('parent_id')......的判断逻辑不完整,没有验证parent_id是否为有效数字,导致无效值进入后续查询逻辑。

修复步骤

  1. 完善POST参数校验
    修改views中的POST判断逻辑,确保parent_id存在且是有效数字:

    if request.method=='POST':
        parent_id_str = request.POST.get('parent_id', '').strip()
        # 验证parent_id是否为有效数字,同时确保name字段存在
        if parent_id_str.isdigit() and request.POST.get('name'):
            parent_id = int(parent_id_str)
            parent_location = customer_location.objects.get(id=parent_id)
            # 后续保存逻辑不变
    
  2. 处理GET请求的parent_id来源
    如果state页面是从其他页面跳转过来(比如选择国家后进入州页面),应该从GET参数中获取parent_id,而不是默认设为None:

    def Insertrecord_state(request):
        parent_id = request.GET.get('parent_id')  # 从URL的GET参数获取
        # 验证parent_id是否为有效数字,无效则设为None或提示用户
        if parent_id and not parent_id.strip().isdigit():
            parent_id = None
        
        # 后续POST逻辑不变
    
  3. 使用安全的查询方式
    用get_object_or_404替代get,避免因无效id直接抛出异常,而是返回404页面,更友好:

    from django.shortcuts import get_object_or_404
    
    # 替换原有的get语句
    parent_location = get_object_or_404(customer_location, id=parent_id)
    
  4. 模板中处理空值
    确保input的value在parent_id为None时显示为空,而不是字符串'None':

    <input type="text" value="{{ parent_id|default:'' }}" name="parent_id" class="form-control" id="inputEmail3" required/>
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 10:10:13