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

Django报错:Cannot assign "123": "Photo.year"必须是Year实例

Django报错:Cannot assign "123": "Photo.year" must be a "Year" instance 解决方法

错误原因

你的Photo模型中year字段是ForeignKey类型,关联了Year模型。这意味着给Photo.year赋值时,必须传入**Year模型的实例对象**,而你现在直接传入了从POST请求获取的字符串"123"(request.POST.get()返回的是字符串类型),不符合Django ForeignKey的赋值要求。

两种解决方法

方法1:先获取Year实例再赋值

修改views.py中创建Photo的代码,先通过id查询到对应的Year实例,再赋值给Photo的year字段:

def photo_create_view(request):
    form = AddPhotoForm()
    if request.method == 'POST':
        image = request.FILES['image']
        thumbnail = request.FILES['image']
        title = request.POST.get('title')
        description = request.POST.get('description')
        year_id = request.POST.get('year')
        people = request.POST.get('people')
        tags = request.POST.get('tags')
        
        # 获取Year实例,建议添加异常处理避免不存在的情况
        try:
            year_instance = Year.objects.get(id=year_id)
        except Year.DoesNotExist:
            # 这里可添加错误处理逻辑,比如返回错误提示
            pass
        
        photo = Photo(
            image=image, 
            thumbnail=thumbnail, 
            title=title, 
            description=description, 
            year=year_instance,  # 传入Year实例
            people=people, 
            tags=tags, 
            submitter=request.user
        )
        photo.save()
        return redirect('/photo/?page=1')
    return render(request, 'photoapp/create.html', context={'form':form})

方法2:直接使用year_id字段赋值

Django会为每个ForeignKey字段自动生成一个xxx_id的字段(比如这里的year对应year_id),可以直接给这个字段赋值id:

def photo_create_view(request):
    form = AddPhotoForm()
    if request.method == 'POST':
        image = request.FILES['image']
        thumbnail = request.FILES['image']
        title = request.POST.get('title')
        description = request.POST.get('description')
        year_id = request.POST.get('year')
        people = request.POST.get('people')
        tags = request.POST.get('tags')
        
        photo = Photo(
            image=image, 
            thumbnail=thumbnail, 
            title=title, 
            description=description, 
            year_id=year_id,  # 直接赋值id
            people=people, 
            tags=tags, 
            submitter=request.user
        )
        photo.save()
        return redirect('/photo/?page=1')
    return render(request, 'photoapp/create.html', context={'form':form})

注意事项

  • request.POST.get('year')返回的是字符串类型,Django会自动将其转换为整数用于查询或赋值year_id,无需手动转换。
  • 建议添加异常处理逻辑,避免传入无效的year_id导致程序崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 07:11:04