简体   繁体   中英

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?

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})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM