如何将焦点设置为django表单元素的CharField

时间:2011-11-24 10:12:53

标签: javascript jquery python django

我在登录页面使用Django的表单。 I want to set focus to the first textField (username) when the page loads.我尝试使用Jquery如下,但是没有得到结果。

forms.py:
from django import forms
class LoginForm(forms.Form):
    userName = forms.EmailField(max_length=25)     
    password = forms.CharField( widget=forms.PasswordInput, label="password" )

的login.html

% block headextra %}
    <script type="text/javascript">
        $(document).ready(function() {
             window.onload = function() {
             $("#id_username").focus();
             // alert('test') if I add this line its works
             //  setting focus to a textbox which added to template page direcltly using html tag the focus() method works well
            };  
        }); 
        </script>       
    {% endblock %}

{% block content %} 
<form method = "POST" action ="/login/">{% csrf_token %}
<table align ="center">
    {{ form.as_table }}
<tr><td></td></tr>
<tr><td><input type="submit" value="Submit"></td></tr>
</table>
</from>

5 个答案:

答案 0 :(得分:13)

正确的Django回答这个问题的方法如下(因为它不依赖于启用js):

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

此外,为了记录,我们避免使用camelcase作为对象属性。干杯!

答案 1 :(得分:2)

我只想使用默认的Django登录表单,但添加了autofocus属性,因此我从默认值中派生了一个新的表单类。

#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': ''})

然后我在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'),
    #...
    )

答案 2 :(得分:2)

在html中,您需要的是autofocus,不带参数。

在Django表单中,将自动对焦添加为具有空值的键:

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

答案 3 :(得分:1)

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

用于输入文字:

    field = forms.CharField(
        widget=forms.TextInput(attrs={'autofocus': 'autofocus'}))

答案 4 :(得分:0)

$("#id_username")应为$("#id_userName")