[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!

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'),
    #...
    )

Leave a comment