我有一个表单,我在模板的嵌套 for 循环中调用它。
这是forms.py
class SubCategoryItemForm(forms.Form):
paragraf = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control'}), required=True, label="Paragraf")
name = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control'}), required=True)
description = forms.CharField(widget=CKEditorWidget(attrs={'class' : 'form-control'}), required=True)
视图.py
def category_view(request, cat_id):
category = Category.objects.get(id=cat_id)
context = {"category": category, "sub_category_item_form": SubCategoryItemForm()}
return render(request, 'registered/category.html', context=context)
在模板中(没有 html):
{{ category.name }}
{{ category.description }}
{% for subcat in category.foreign_category.all %}
{{ subcat.name }}
{{ subcat.description }}
<form role="form" id="{{ subcat.id }}" action="{% url 'auth_sub_category_item_add' %}" method="POST">
{% csrf_token %}
{{ sub_category_item_form }}
<button type="submit">Save</button>
</form>
{% endfor %}
问题:我不知道如何将表单字段 id 设置为唯一。因为子类别中可能有多达 15 个这种形式。具体来说,描述表单字段需要一个唯一的 id。表单发布并保存,但从 CKEditorWidget 得到一个烦人的 js 错误:
Uncaught The editor instance "id_description" is already attached to the provided element.
我可以通过编辑 js 来抑制这一点,但很高兴知道是否有任何方法可以动态设置字段 id。