【发布时间】:2020-01-11 20:34:58
【问题描述】:
我很困惑为什么当我运行这段代码时它会返回一个错误
create() 接受 1 个位置参数,但给出了 2 个
if request.method == "POST":
my_form = RawProductCreateForm(request.POST)
if my_form.is_valid():
Product.objects.create(my_form.cleaned_data)
但是当我修改 create 方法并在传递清理后的数据之前添加 ** 时,它可以工作!
Product.objects.create(**my_form.cleaned_data)
【问题讨论】:
-
把模型和表格也贴出来
-
阅读
objects.create上的文档:docs.djangoproject.com/en/2.2/ref/models/querysets/#create 它只接受model_prop=value形式的关键字参数,没有位置参数。 python 中的**运算符将字典作为关键字参数应用于函数。见stackoverflow.com/questions/36901/…。 -
如果您的
RawProductCreateForm是ModelForm,您可以使用 the save method 创建 Product 对象,例如my_form.save()
标签: python django cleaned-data