简体   繁体   中英

Remove autofocus attribute from field in Django

I'm working on a sign up form, I have a few custom fields before the username. What's happening is that by default the focus is on the username field and I can't remove the autofocus attribute from this field.

I know I can work around using JavaScript but I'm trying to do this in the right way on Django.

from django import forms
from django.contrib.auth.models import User
from project.userprofile.models import UserProfile

class UserSignupForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(UserSignupForm, self).__init__(*args, **kwargs)
        self.fields['username'].widget.attrs['autofocus'] = 'off'

Did I miss something?

UPDATE

The solution is:

self.fields['username'].widget.attrs.pop("autofocus", None)

Thanks @mariodev!

(From a comment by @mariodev)

You should be able to do:

self.fields['username'].widget.attrs.pop("autofocus", None)

to remove the item from the attrs collection iff the specified item exists.

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