Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Set focus to CharField of a django form element

Am using Django's form for my login page. 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.

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>
like image 689
Jisson Avatar asked Nov 24 '11 10:11

Jisson


People also ask

What is CharField in Django?

CharField is a string field, for small- to large-sized strings. It is like a string field in C/C+++. CharField is generally used for storing small strings like first name, last name, etc. To store larger text TextField is used. The default form widget for this field is TextInput.

How do you make a field not editable in Django?

disabled. The disabled boolean argument, when set to True , disables a form field using the disabled HTML attribute so that it won't be editable by users. Even if a user tampers with the field's value submitted to the server, it will be ignored in favor of the value from the form's initial data.

How do you make a field optional in Django?

If you want to allow blank values in a date field (e.g., DateField , TimeField , DateTimeField ) or numeric field (e.g., IntegerField , DecimalField , FloatField ), you'll need to use both null=True and blank=True . Save this answer. Show activity on this post. Use null=True and blank=True in your model.

What is forms Modelform in Django?

Django Model Form It is a class which is used to create an HTML form by using the Model. It is an efficient way to create a form without writing HTML code. Django automatically does it for us to reduce the application development time.


2 Answers

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': ''}))
like image 172
Ramon Avatar answered Oct 13 '22 01:10

Ramon


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!

like image 25
Williams Avatar answered Oct 13 '22 00:10

Williams