[Fixed]-How Set focus to CharField of a django form element

2๐Ÿ‘

โœ…

$("#id_username") should be $("#id_userName")

27๐Ÿ‘

The proper Django way of answering this question is as follows (as it doesnโ€™t depend on js being enabled):

from django import forms

class LoginForm(forms.Form):
    user_name = forms.EmailField(max_length=25)     
    password = forms.CharField( widget=forms.PasswordInput, label="password" )

    def __init__(self):
        self.fields['user_name'].widget.attrs.update({'autofocus': 'autofocus'
            'required': 'required', 'placeholder': 'User Name'})
        self.fields['password'].widget.attrs.update({
            'required': 'required', 'placeholder': 'Password'})

Also, for the record, we avoid the use of camelcase for object attributes. Cheers!

๐Ÿ‘คWilliams

12๐Ÿ‘

    password = forms.CharField(
        widget=forms.PasswordInput(attrs={'autofocus': 'autofocus'}))

for text input:

    field = forms.CharField(
        widget=forms.TextInput(attrs={'autofocus': 'autofocus'}))
๐Ÿ‘คint_ua

6๐Ÿ‘

In html, all you need is autofocus without arguments.

In the Django form, add autofocus as key with empty value:

search = forms.CharField(
                label='Search for:',
                max_length=50,
                required=False,
                widget=forms.TextInput(attrs={'autofocus': ''}))
๐Ÿ‘คRamon

2๐Ÿ‘

I just wanted to use the default Django login form, but add the autofocus attribute, so I derived a new form class from the default.

#myapp/forms.py
from django.contrib.auth.forms import AuthenticationForm

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

Then I specified the new form class in urls.py:

from myapp.forms import LoginForm

urlpatterns = patterns(
    '',
    url(r'^login/$', 'django.contrib.auth.views.login',
        {"template_name": "myapp/login.html",
         "authentication_form": LoginForm,
         "current_app": "myapp"}, name='login'),
    #...
    )
๐Ÿ‘คDon Kirkby

Leave a comment