简体   繁体   English

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

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

Am using Django's form for my login page.我的登录页面使用 Django 的表单。 I want to set focus to the first textField (username) when the page loads. I tried using Jquery as follows, But doen't get the result.我尝试使用 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登录.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>

The proper Django way of answering this question is as follows (as it doesn't depend on js being enabled):回答这个问题的正确 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'})

Also, for the record, we avoid the use of camelcase for object attributes.此外,为了记录,我们避免对对象属性使用驼峰式大小写。 Cheers!干杯!

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

for text input:对于文本输入:

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

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

Then I specified the new form class in urls.py :然后我在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'),
    #...
    )

In html, all you need is autofocus without arguments.在 html 中,您所需要的只是不带参数的autofocus

In the Django form, add autofocus as key with empty value:在 Django 表单中,添加 autofocus 作为键,值为空:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在任何引导模式中将焦点设置在第一个表单元素上 - How to set focus on first form element in any bootstrap modal 如何将焦点设置为表单中的第一个可编辑输入元素 - how to set focus to first editable input element in form 如何使用JavaScript将焦点设置为表单中的某个元素? - How can I set the focus to a certain element in a form using JavaScript? 提交和重置表单后如何在输入元素中设置焦点? - How to set focus in an input element after submit and reset form? 如何使用 JavaScript 将焦点设置在 HTML 表单中的元素上? - How can I set focus on an element in an HTML form using JavaScript? 如何将光标聚焦在表单元素上? - How to focus cursor on form element? 验证后将焦点设置为文本框表单元素 - set focus to textbox form element following Validation 使用 JavaScript / RichFaces 将焦点设置到表单元素 - Set focus to a form element using JavaScript / RichFaces 为什么 Django 允许用户输入<script>alert("hello")</script> 在表单 CharField 没有抛出错误? - How come Django allows user to enter <script>alert("hello")</script> in form CharField without throwing an error? 如何将焦点设置为独立于 id 的 HTML 表单中的第一个输入元素? - How do I set the focus to the first input element in an HTML form independent from the id?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM