将表单属性添加到输入字段

adding form attribute to inputfield

我正在尝试提交一个表单,其中的输入字段在表单之外(see here). Therefore I want to add the form="" attribute to my inputfields, as described :

class TestForm(forms.Form):
    class Meta:
        model = Product
        fields = ["number"]
        
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["number"] = forms.IntegerField(required = True)
        self.fields["number"].widget.attrs.update({"class": "form-control w-50"}) ## works
        self.fields["number"].widget.attrs.update({"form": "testformid"}) ## does not work

在模板中,输入字段呈现为:

<input type="number" name="number" value="8" class="form-control w-50" required="" id="id_number">

如何正确添加 form="..."

尝试使用数据属性并使用一个更新调用

class TestForm(forms.Form):
    class Meta:
        model = Product
        fields = ["number"]
        
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["number"] = forms.IntegerField(required = True)
        self.fields["number"].widget.attrs.update({"class": "form-control w-50","data-form": "testformid"})