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

风格不统一 提交于 2021-02-11 17:35:42

问题


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.


回答1:


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




回答2:


Change the variable name.

class SignupForm(UserCreationForm):
        email_address = forms.EmailField()



回答3:


You can define your form manually and write the attribute names yourself:

<form method="post"> 
    {% csrf_token %}
    <input type="text" name="email_address">
    <input type="text" name="username"> <!-- for example -->
    <button type="submit" value="Submit"></button>
</form>


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!