Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
97 views
in Technique[技术] by (71.8m points)

How do I change the 'name' HTML attribute of a Django Form field?

I have a Django 3.0 form

# forms.py
class SignupForm(UserCreationForm):
    email = forms.EmailField()

This renders as the HTML element

<input type="text" name="email" required id="id_email">

Is there a way to change the 'name' attribute?

The widgets documentation suggests that either of these might work:

# forms.py
class SignupForm(UserCreationForm):
    email = forms.EmailField(
        widget = forms.TextInput(
            attrs = {'name': 'email_address'}
        )
    )

or

# forms.py
class SignupForm(UserCreationForm):
    email = forms.EmailField()

    email.widget.attrs.update({'name': 'email_address'})

but both render with two name attributes; the first one isn't replaced:

<input type="text" name="email" name="email_address" required id="id_email">

Is there a straightforward method of changing the name attribute?

I've found a couple of related previous posts, but the questions and answers tend to be old (Django 1.0-era) and more convoluted than this process ought to be. I'm hoping that newer versions have a simpler solution.

question from:https://stackoverflow.com/questions/65861544/how-do-i-change-the-name-html-attribute-of-a-django-form-field

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can override the add_prefix method in your SignupForm to get the desired output

Update your form like this

class SignupForm(UserCreationForm):
    custom_names = {'email': 'email_address'}

    def add_prefix(self, field_name):
        field_name = self.custom_names.get(field_name, field_name)
        return super(SignupForm, self).add_prefix(field_name)
        
    email = models.CharField(max_length=100)

to get a little insight of add_prefix method check this out


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...