【问题标题】:How Set focus to CharField of a django form element如何将焦点设置到 django 表单元素的 CharField
【发布时间】:2012-01-05 12:31:12
【问题描述】:

我的登录页面使用了 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" )

登录.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>

【问题讨论】:

    标签: javascript jquery python django


    【解决方案1】:

    $("#id_username") 应该是$("#id_userName")

    【讨论】:

      【解决方案2】:

      正确的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'})
      

      另外,为了记录,我们避免使用驼峰式来表示对象属性。干杯!

      【讨论】:

      • 我还没有找到一个使用表单而不是视图为 django 明确实现 LoginForm 的地方。能否请您分享其余的实施。您如何从视图中调用此表单等。谢谢。
      • Heya @jangeador 我不久前开始了一个项目,这里有一个完整的自定义用户模型的基本实现:github.com/elena/django-starterkit-userauth——这仍然是 alpha,但可能提供了你正在寻找的示例为了。干杯!
      • @jangeador 确切表格的链接在这里:github.com/elena/django-starterkit-userauth/blob/master/…
      • 我更喜欢使用 attrs.update(autofocus='autofocus')attrs.update(autofocus='') 语法(因为值不相关)。将关键字参数传递给.update() 在语法上更简单。
      【解决方案3】:

      我只是想使用默认的 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'),
          #...
          )
      

      【讨论】:

        【解决方案4】:
            password = forms.CharField(
                widget=forms.PasswordInput(attrs={'autofocus': 'autofocus'}))
        

        文本输入:

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

        【讨论】:

        • 在回答旧主题时请注意多个答案,尤其是其中一个已被接受时。你需要解释为什么你的答案比现有的任何一个都好。
        • 另外,您需要支持您的示例代码,并说明它如何解决 OP 的问题。帮助他人理解。
        • 我没有时间,抱歉。看了相关的Django文档我觉得还是挺明显的。
        • 你已经是 StackOverflow 的成员很久了,现在你应该知道它是如何工作的了。没有人强迫你在这里回答问题。如果您选择回答问题,那么您的答案将被更广泛的社区评估。
        【解决方案5】:

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

        在 Django 表单中,添加 autofocus 作为 key,值为空:

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

        【讨论】:

        • {'autofocus': True} 也可以。
        猜你喜欢
        • 2020-03-27
        • 2015-11-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-27
        • 2013-07-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多