使用django模板更改form字段的name属性 [英] Change the name attribute of form field in django template using
问题描述
我有表单域 {{form.item}} ,它将呈现到
I have form field {{form.item}} which will render to
<input type="text" name="item" >
如何使用自定义模板标签更改表单字段的名称属性?
How can i change the name attribute of the form field using custom template tags?
我尝试将表单发送到模板标签,其中
I tried by sending the form to template tag where
form.fields['item'].widget.attrs['name'] = 'new_name'
但是我没有得到成功。
我需要更改模板中的name属性。
I need to change the name attribute in template.
更新
models.py
class A(models.Model):
name = models.CharField(50)
type = models.CharField(50)
class B(models.Model):
field1 = ForeignKeyField(A)
value = IntegerField()
py
def saving_calculation(request):
SavingFormset = modelformset_factory(A, extra=2)
OfferInlineFormSet = inlineformset_factory(
A, B,
extra = 4
)
if request.method == 'POST':
pass
else:
offer_formset = OfferInlineFormSet()
saving_formset = SavingFormset(queryset=SavingCalculation.objects.none())
return render_to_response(
'purchasing/saving_calculation.html',
{
'offer_formset':offer_formset,
'saving_formset':saving_formset,
}
模板
<form action="." method="POST">
{{ offer_formset.management_form }}
{{ saving_formset.management_form }}
{{ saving_formset.prefix }}
<table>
<thead>
<tr>
<th>Business Unit</th>
<th>Category</th>
<th>Buyer</th>
<th>Offer1</th>
<th>Offer2</th>
<th>Offer3</th>
<th>Offer4</th>
</tr>
</thead>
<tbody>
{% for saving in saving_formset.forms %}
<tr>
<td>{{saving.businessunit}}</td>
<td>{{saving.type_of_purchase}}</td>
<td>{{saving.buyer}}</td>
{% for offer in offer_formset.forms %}
<td>{{ offer|set_field_attr:forloop.counter0 }}</td>
</tr>
{% endfor %}
{% endfor %}
</tbody>
</table>
<input type="submit" value="Save" />
</form>
现在在自定义模板标签中,我需要为内联表单集合的每个字段分配新名称
Now in custom template tag i need to assign new name for each field of inline formset
推荐答案
我已经通过几种不同的方式进行了测试,它可以与许多类型的表单字段一起使用。
I've tested this a few different ways, and it works with many types of Form Fields.
在要设置名称的每个字段上使用 set_field_html_name(...)
。
Use set_field_html_name(...)
on every Field you want to set the name on.
from django import forms
from django.core.exceptions import ValidationError
def set_field_html_name(cls, new_name):
"""
This creates wrapper around the normal widget rendering,
allowing for a custom field name (new_name).
"""
old_render = cls.widget.render
def _widget_render_wrapper(name, value, attrs=None):
return old_render(new_name, value, attrs)
cls.widget.render = _widget_render_wrapper
class MyForm(forms.Form):
field1 = forms.CharField()
# After creating the field, call the wrapper with your new field name.
set_field_html_name(field1, 'new_name')
def clean_field1(self):
# The form field will be submit with the new name (instead of the name "field1").
data = self.data['new_name']
if data:
raise ValidationError('Missing input')
return data
这篇关于使用django模板更改form字段的name属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!