question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Search Input not receiving focus

See original GitHub issue

I have a really odd problem that I can’t seem to nail down the cause. I am using DAL v3.2.7 with Django 1.11.1. In one of my forms, I am trying to create a form whereby the user can add a person, and then choose the department that the person belongs to. There is a FK field on Person -> Department, and M2M fields for Person <-> AccessLevel, Key. The issue lies with the autocomplete for Department. While the form renders nicely in my modal component (I use django-fm and crispy forms), and the Department is successfully queried and results are populated in the select2 dropdown, the search input cannot receive focus and won’t allow any input for autocompletion. The funny thing is, my ModelSelect2Multiple widgets work fine! There is one last interesting thing that is happening, and that is when I have the field selected in the UI, and the dropdown is open, if I hit the Esc key and the modal window is closed, the entire widget remains on screen and the input element receives focus and the autocomplete works like a charm! I don’t receive any errors anywhere, either from the Chrome Dev Tools, Django Debug Toolbar, nor from the system console where I have django running.

Here is the relevant code in my app:

models.py

class Department(models.Model):
    history = AuditlogHistoryField()

    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

    class Meta:
        ordering = ['name']

class AccessLevel(models.Model):
    history = AuditlogHistoryField()

    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

    class Meta:
        ordering = ['name']

class Key(models.Model):
    history = AuditlogHistoryField()

    number = models.PositiveSmallIntegerField()

    class Meta:
        ordering = ['number']

class Person(models.Model):
    history = AuditlogHistoryField()

    name = models.CharField(max_length=100)
    escort_req = models.BooleanField()
    department = models.ForeignKey(Department, related_name='pers_dept')
    levels = models.ManyToManyField(AccessLevel, related_name='access_levels', related_query_name='level')
    keys = models.ManyToManyField(Key, related_name='key_list', related_query_name='key')

    class Meta:
        ordering = ['name']

department_urls.py

# ...
url(r'^autocomplete/$',
        login_required(DepartmentAutocomplete.as_view()),
        name="department_autocomplete"),
# ...

department_views.py

# ...
class DepartmentAutocomplete(autocomplete.Select2QuerySetView):
    def get_queryset(self):
        if not self.request.user.is_authenticated():
            return Department.objects.none()

        qs = Department.objects.all()

        if self.q:
            qs = qs.filter(name__icontains=self.q)

        return qs
# ...

forms.py

# ...
class PersonForm(autocomplete.FutureModelForm):
    department = forms.ModelChoiceField(
        queryset=Department.objects.all(),
        widget=autocomplete.ModelSelect2(url='department_autocomplete')
    )
    levels = forms.ModelMultipleChoiceField(
        queryset=AccessLevel.objects.all(),
        widget=autocomplete.ModelSelect2Multiple(url='access_level_autocomplete')
    )
    keys = forms.ModelMultipleChoiceField(
        queryset=Key.objects.all(),
        widget=autocomplete.ModelSelect2Multiple(url='key_autocomplete')
    )
    escort_req = forms.BooleanField(required=False)

    class Meta:
        model = Person
        fields = ['name', 'escort_req', 'department', 'levels', 'keys']
        labels = {
            'escort_req': 'Escort Required?'
        }

    def __init__(self, *args, **kwargs):
        super(PersonForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.form_tag = True
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-sm-3'
        self.helper.field_class = 'col-sm-9'
        self.helper.layout = Layout(
            Field('name'),
            Field('escort_req'),
            Field('department'),
            Field('levels'),
            Field('keys'),
        )
# ...

I really appreciate any kind of help the community can provide! I will continue doing what I can to see if I can figure out the problem. Could it possibly be a problem with my front-end dependencies? It doesn’t seem to be a problem on the backend, since the ModelSelect2Multiple widgets work just fine. I’m stumped.

Issue Analytics

  • State:open
  • Created 6 years ago
  • Comments:11 (4 by maintainers)

github_iconTop GitHub Comments

2reactions
serguituscommented, Apr 4, 2020

I know this discussion is old but I still faced the same issue today. as @Madalosso pointed, it IS a Select2 issue. There is a SO discussion on solutions to this. Even if there is a dirty hack to deal with this (removing tabindex=“-1” on your modal HTML) I think this is something that DAL should fix (and can fix easily) I did some research on the code and propose this couple lines at ./select2.js#72 to fix this:

parent = $(this).attr('dropdownParent') || 'body';
$(this).select2({
            dropdownParent: $(parent),

Note I just added the option to set dropdownParent parameter on Select2 Initialization so it can be set on widget definition via

       widget=autocomplete.ModelSelect2(
            attrs={'dropdownParent': '.modal-content'},
        ),

and it just works 😃 @jpic, what do you think about it?

1reaction
jpiccommented, Jun 28, 2017

If anybody reproduces this in the test_project i’ll take a look.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Why would the search input field not get focus when the page ...
Opening up google.com I see that the search input field gets focus automatically, i.e. the cursor is already blinking ...
Read more >
jquery mobile - Search input focus not work - Stack Overflow
1 Answer 1 ... Are you using unique ID's? If you are using a "text" input element try using keyup instead of mouseup....
Read more >
Search not auto focusing in jQuery 3.6.0 · Issue #5993 - GitHub
I'm running Select2 4.0.13 with jQuery 3.6.0 and the search box does not auto-focus when opening select2. I believe this is caused by...
Read more >
HTMLElement.focus() - Web APIs | MDN
The HTMLElement.focus() method sets focus on the specified element, if it can be focused. The focused element is the element that will ...
Read more >
.focus() | jQuery API Documentation
Therefore, scripts that rely on event delegation with the focus event will not work consistently across browsers. As of version 1.4.2, however, jQuery...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found