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

Viewed 1099

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.

3 Answers

Change the variable name.

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

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

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>
Related