Django表单添加初始数据到绑定表单

xggvc2p6  于 2023-05-08  发布在  Go
关注(0)|答案(2)|浏览(254)

我试图将初始数据从一个表单添加到第二个表单中,但似乎无法使其工作。我尝试过不同的方法,但最接近的方法来自this post
这是我的代码

if request.method == 'POST':
    laptop_select_form = LaptopSelectForm(request.POST)
    if laptop_select_form.is_valid():
        laptop_model_id = literal_eval(laptop_select_form.cleaned_data['model'])[0]

        laptop_for_parts_form = LaptopForPartsForm(request.POST, laptop_id=laptop_model_id)

    if laptop_for_parts_form.is_valid():
else:
    laptop_select_form = LaptopSelectForm()
    laptop_for_parts_form = LaptopForPartsForm()

还有表格

class LaptopForPartsForm(forms.ModelForm):
def __init__(self, laptop_id=0, *args, **kwargs):
    super(LaptopForPartsForm, self).__init__(*args, **kwargs)
    self.laptop_id = laptop_id

class Meta:
    model = LaptopForParts
    fields = ('__all__')
    widgets={'laptop_id': forms.HiddenInput()}

但我一直得到这个错误:

laptop_for_parts_form = LaptopForPartsForm(request.POST, laptop_id=laptop_model_id)
TypeError: __init__() got multiple values for argument 'laptop_id'

有没有更有经验的人能给我指出正确的方向?

j5fpnvbx

j5fpnvbx1#

我更改了request.POST数据,并在表单验证之前添加了laptop_id

if request.method == 'POST':
    laptop_select_form = LaptopSelectForm(request.POST)
    if laptop_select_form.is_valid():
        # Get laptop model ID from laptop_select_form
        laptop_model_id = literal_eval(laptop_select_form.cleaned_data['model'])[0]

        # Change immutable request.POST form data to add model ID
        _mutable = request.POST.copy()
        _mutable['laptop_id'] = laptop_model_id

        laptop_for_parts_form = LaptopForPartsForm(_mutable)

    if laptop_for_parts_form.is_valid():
        laptop_for_parts_form.save()
else:
    laptop_select_form = LaptopSelectForm()
    laptop_for_parts_form = LaptopForPartsForm()
efzxgjgh

efzxgjgh2#

我怀疑错误got multiple values for argument 'laptop_id'源于您向LaptopForPartsForm提供了两次'laptop_id'参数。您首先在request.POST中隐式地提供了'laptop_id'参数,然后通过声明laptop_id=laptop_model_id再次显式地提供了它。
您可以通过只提供一次'laptop_id'参数来解决这个问题,例如:

laptop_for_parts_form = LaptopForPartsForm(laptop_id=laptop_model_id)

相关问题