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

求助:PyCharm CE中Django代码的('products':products)出现Unexpected expression syntax错误

问题原因与修复方案

你的语法错误出在render函数的第三个参数上:你用了圆括号()来包裹键值对,但Python里定义字典需要用大括号{},圆括号只能用来定义元组,而元组里不能出现key: value这种字典语法,所以才会报Unexpected expression syntax错误。

修复后的代码如下:

from django.shortcuts import render
from django.http import HttpResponse
from .models import Product

def admin_console(request):
    products = Product.objects.all()
    return render(request, 'products/products_page.html', {'products': products})

另外,当上下文的键名和变量名完全一致时,还可以用更简洁的关键字参数写法:

return render(request, 'products/products_page.html', products=products)

两种写法都能正常将products数据传递到模板中使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 23:31:17