create() 接受 1 个位置参数,但给出了 2 个?姜戈

Ayo*_*oub 2 python django cleaned-data

我很困惑为什么当我运行这段代码时它会返回一个错误

create() 接受 1 个位置参数,但给出了 2 个

if request.method == "POST":
my_form = RawProductCreateForm(request.POST)
if my_form.is_valid():
    Product.objects.create(my_form.cleaned_data)
Run Code Online (Sandbox Code Playgroud)

但是当我修改 create 方法并在传递清理过的数据之前添加 ** 时它起作用了!

Product.objects.create(**my_form.cleaned_data)
Run Code Online (Sandbox Code Playgroud)

Mat*_*ser 5

这是因为create需要关键字参数,例如

    Product.objects.create(product_name="Dish Soap", product_price=73)
Run Code Online (Sandbox Code Playgroud)

将 放在**它之前告诉模型将其my_form.cleaned_data视为关键字参数的字典。