在我的模板中,我有:
{% for link in solution_list %}
<form id="marked_solved_form{{link.id}}" action="" method="post">
{{mark_solved_form.is_solution}}
{% csrf_token %}
<label for="id_is_solution{{link.id}}">test form</label>
<input type="hidden" name="next" value="{{ request.path }}"/>
</form>
{% endfor %}
is_solution 只是用户可以设置的复选框的布尔字段。
我面临的问题是,除了 {{mark_solved_form.is_solution}} 之外,所有表单都使用 id 正确填充,例如 id="marked_solved_form3"。我想我可以去模型表单并编辑属性:
class PostMarkedSolved(ModelForm):
class Meta:
model = MarkedSolved
def __init__(self, *args, **kwargs):
super(PostMarkedSolved, self).__init__(*args, **kwargs)
#self.fields['is_solution'].queryset = Factory.objects.all()
self.fields['is_solution'].widget.attrs={'onchange':'this.form.submit();', 'class':'testing{{link.id}}', 'id':'testing{{link.id}}'}
到目前为止,一切都很好。除了表单加载时,我为每个列表表单中的每个复选框得到以下信息:
<input name="is_solution" type="checkbox" class="testing{{link.id}}" onchange="this.form.submit();" id="testing{{link.id}}">
就好像 django 忽略了 modelform 正在一起转义模板标签 {{link.id}} 。理想情况下,它会为每个表单实例返回如下内容:
<td>
<form id="marked_solved_form3" action="" method="post">
<input name="is_solution" type="checkbox" class="testing3" onclick="this.form.submit();" id="testing3" />
<div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='bwuXYhSpQA8yEOEPSaCt3wAANC0kR7CE' /></div>
<label for="id_is_solution3" onclick="this.form.submit();">test form</label>
<input type="hidden" name="next" value="/task/1"/>
</form>
</td>
<td>
<form id="marked_solved_form4" action="" method="post">
<input name="is_solution" type="checkbox" class="testing4" onclick="this.form.submit();" id="testing4" />
<div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='bwuXYhSpQA8yEOEPSaCt3wAANC0kR7CE' /></div>
<label for="id_is_solution4" onclick="this.form.submit();">test form</label>
<input type="hidden" name="next" value="/task/1"/>
</form>
</td>
我什至安装了 django-widget-tweaks (这太棒了,顺便说一句!),并尝试这样做:
{{mark_solved_form.is_solution|attr:"id:id_is_solution{{link.id}}"}}
然而,这令人窒息,因为它无法在另一个模板标签中处理 {{link.id}}。:( 任何建议将不胜感激。在此先感谢!