在模板中循环遍历模型时,如何将唯一 id 字段从模型传递到 Django 表单?

How can I pass unique id fields from a Model to a Django form when looping through model in a template?

我需要为从 Django 模板中的循环生成的每个表单创建唯一 ID。我使用 {% for product in products %} 循环遍历一些数据。在我的 forms.py 中,我将 form.widget.Select 属性编辑为 add/change onchangeid 字段。我通过 views.py 和我的模板将其呈现为 {{form}},这是 forms.py 中的行:

condition = forms.ChoiceField(choices=condition_choices, widget=forms.Select(attrs={'onchange' : "showChange(this)", "id":"{{product.id}}"}))

我希望 id 呈现为与每个产品关联的唯一 id,并且我希望 onchange 调用 js 函数。当我将表单打印到控制台时,它看起来像这样:

<select name="condition" onchange="showChange(this)" id="{{product.id}}">
  <option value="NM / LP">Near Mint / Lightly Played</option>

  <option value="MP">Moderately Played</option>

  <option value="HP">Heavily Played</option>

  <option value="Damaged">Damaged</option>

  <option value="Unopened">Unopened</option>

</select>

我希望 id 字段是实际的 id 而不是 {{product.id}} 如果将此表单准确粘贴到 html 中而不将其呈现为 Django 表单,则它会按预期工作。如何在不将数据库导入 forms.py/extra 数据库调用的情况下将产品的唯一 ID 传递给 Django 表单?

您不能在 .py 文件中使用 {{product.id}}。这是一个 Django 模板引擎标签。

在您的 views.py 中,您应该像这样创建表单:

product = Product.objects.get(pk=1)

form = ProductForm(instance=product)

context = {
    'form': form
}

当您传递表单时,您可以在 __init__ 方法中使用它的数据。

您的表单将如下所示

class ProductForm(forms.ModelForm):

class Meta:
    model = Product
    exclude = ()

def __init__(self, *args, **kwargs):
    super(ProductForm, self).__init__(*args, **kwargs)
    instance = kwargs['instance']
    self.fields['condition'].widget.attrs['id'] = instance.id