Reputation: 313
In the following template, how do I force the cursor to autofocus into the form.username field when the browser loads?
{% block content %}
<form method="post" action="">
{% csrf_token %}
<table>
<tr>
<td>{{ form.username.label_tag }}</td>
<td>{{ form.username }}</td>
</tr>
<tr>
<td>{{ form.password.label_tag }}</td>
<td>{{ form.password }}</td>
</tr>
</table>
<input type="submit" value="login" style="position: relative; left: 5em;" />
<input type="hidden" name="next" value="{{ next }}" />
</form>
<p><a href="/register/" class="textf" style="position: relative; left: 8em;">Register</a></p>
{% endblock %}
Upvotes: 2
Views: 3852
Reputation: 1806
In your forms.py define the field with the autofocus attribute:
username = forms.CharField(
label=_('Username'),
strip=True,
widget=forms.TextInput(attrs={'placeholder': _('Username'), 'class': 'form-control', 'autofocus': True})
)
https://docs.djangoproject.com/en/2.1/ref/forms/widgets/#django.forms.Widget.attrs
Upvotes: 3
Reputation: 17249
You could just do it with javascript (in this example, Jquery). Make sure there is a block called extra_scripts in your base.html (just above the closing </body>
tag), and then add the javascript as follows:
{% block content %}
<form method="post" action="">
{% csrf_token %}
<table>
<tr>
<td>{{ form.username.label_tag }}</td>
<td>{{ form.username }}</td>
</tr>
...
{% endblock %}
{% block extra_scripts %}
<script type="text/javascript">
$(function () {
// When the page has finished loading,
// autofocus on the username field
$('input#id_username').focus();
});
</script>
{% endblock %}
If you're not already using Jquery you will need to include a link to it in the page too (something like <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
).
Upvotes: 0
Reputation: 893
You can use django-widget-tweaks
<td>{{ form.username|attr:"autofocus" }}</td>
Also it can add attributes and classes, render fields with custom template and more
Upvotes: 1