fredperk
fredperk

Reputation: 818

How to disable autofocus from username field in Django's UserCreationForm?

I am using the UserCreationForm class to create a signup page in my Django app.

Here is my code that defines my SingUpForm:

class SignUpForm(UserCreationForm):
    email = ...
    username = forms.CharField(label="Username",
        widget=forms.TextInput(attrs={
            ...
            "autofocus": False,
            ...
        }))
    password1 = ...
    password2 = ...

Despite the autofocus attribute being set to False, when I open the form in my browser the focus is still on the username field.

How can I disable it?

Upvotes: 2

Views: 1068

Answers (1)

Benbb96
Benbb96

Reputation: 2283

The autofocus is overridden in the __init__ of UserCreationForm (see here).
You should try to use the same technique by adding __init__ in your SignUpForm :

def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.fields['username'].widget.attrs.update({'autofocus': False})

Upvotes: 5

Related Questions