Django密码重置表单自动聚焦失效,登录/注册表单正常的问题求助
Let's break down why your autofocus isn't working and fix it step by step:
1. Your JavaScript Selector Is Targeting the Wrong Element
Looking at your template code, your email input doesn't have an id="id_email" attribute—you're rendering it manually instead of using Django's form field. So this line in your JS:
$('input#id_email').focus();
can't find any element to focus on.
Fix: Either add the id to your input, or use the name attribute to select it:
Option A: Add the ID to the input
Update your template's email input:
<input type="email" name="email" placeholder="Email" class="form-control" value="{{ fieldValues.email }}" id="id_email"/>
Then your existing JS will work as intended.
Option B: Adjust the JS selector
Change your JavaScript to target the input by its name instead:
<script type="text/javascript"> $(document).ready(function () { $('input[name="email"]').focus(); }); </script>
2. You Can Skip JS Entirely with Native HTML Autofocus
The simplest fix is to just add the native autofocus attribute directly to your input tag—no JS or widget_tweaks needed:
<input type="email" name="email" placeholder="Email" class="form-control" value="{{ fieldValues.email }}" autofocus/>
This is supported in all modern browsers and works reliably as long as the input is rendered when the page loads.
3. Why Widget Tweaks Didn't Work
You tried using {{ form.email|attr:"autofocus" }}, but in your template, you're not rendering the email field from a Django form—you're writing the input tag manually. Widget_tweaks only works when you use Django's form field rendering syntax (like {{ form.email }}), so that approach was never going to affect your manual input.
4. Check for Focus Stealing (e.g., Recaptcha)
If you still have issues after the above fixes, it's possible that the Recaptcha widget is stealing focus when it loads. To work around this, you can delay setting the focus until after the page fully loads, or use a small timeout:
<script type="text/javascript"> $(window).on('load', function () { // Wait 100ms to let Recaptcha finish loading setTimeout(() => { $('input[name="email"]').focus(); }, 100); }); </script>
Pick the solution that fits your setup best—adding the native autofocus attribute is the most straightforward.
内容的提问来源于stack exchange,提问作者rob

