更新时间:2023-09-03 15:57:34
我已经通过几种不同的方式进行了测试,它可以与许多类型的表单字段一起使用。
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