Using several autocomplete-light dropdown menus in a Django template

I am in the process of creating a web application that necessitates searching for a specific user record by inputting either the first name OR last name. While two more search attributes will be added in the future, I am currently facing issues with incorporating two autocomplete-light drop-downs in the same template. The crux of the problem lies in the fact that only the second drop-down functions correctly.

Below are the pertinent code snippets (with extraneous code removed). Although this method may not be the most efficient, my main focus is on achieving a functional implementation before delving into optimizations or refactoring.

forms.py

class StudentChoiceFieldLN(forms.Form):

    students = forms.ModelChoiceField(
        queryset=Student.objects.all().order_by("last_name"),
        widget=autocomplete.ModelSelect2(url='student-ln-autocomplete'),
    )

    def __init__(self, *args, **kwargs):
        super(StudentChoiceField, self).__init__(*args, **kwargs)
        self.fields['students'].queryset = Student.objects.all().order_by("last_name")
        self.fields['students'].label_from_instance = lambda obj: "%s %s" % (obj.last_name, obj.first_name)

class StudentChoiceFieldFN(forms.Form):

    students = forms.ModelChoiceField(
        queryset=Student.objects.all().order_by("first_name"),
        widget=autocomplete.ModelSelect2(url='student-fn-autocomplete'),
    )

    def __init__(self, *args, **kwargs):
        super(StudentChoiceFieldFN, self).__init__(*args, **kwargs)
        self.fields['students'].queryset = Student.objects.all().order_by("first_name")
        self.fields['students'].label_from_instance = lambda obj: "%s %s" % (obj.last_name, obj.first_name)

views.py

class StudentLNAutoComplete(autocomplete.Select2QuerySetView):
    def get_queryset(self):

        qs = Student.objects.all()

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

        return qs

class StudentFNAutoComplete(autocomplete.Select2QuerySetView):
    def get_queryset(self):

        qs = Student.objects.all()

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

        return qs

def index(request):
    students_choice_ln = StudentChoiceFieldLN()
    students_choice_fn = StudentChoiceFieldFN()
    
    context = {
        'students_choice_ln': students_choice_ln,
        'students_choice_fn': students_choice_fn,
        'selected_student': None
    }

    return render(request, 'awards/index.html', context)

urls.py

from awards.views import StudentLNAutoComplete
from awards.views import StudentFNAutoComplete

urlpatterns = [
    ...
    path('student-ln-autocomplete/', StudentLNAutoComplete.as_view(), name='student-ln-autocomplete'),
    path('student-fn-autocomplete/', StudentFNAutoComplete.as_view(), name='student-fn-autocomplete'),
    ...
]

awards/index.html

Note the placement of the {{ students_choice_fn.media }} declaration. I attempted to relocate this declaration based on suggestions from related Stack Overflow posts, as I suspect that the issue stems from how the relevant css/javascript for autocomplete-light is rendered, resulting in the malfunction of the first field.

{% extends "base.html" %}

{% block content %}

<body>

{{ students_choice_fn.media }}

<div class="container">

<div class="row">
  <div class="col-md-6">

    <form method=POST action="/awards/select">
        {% csrf_token %}
        
        {{ students_choice_ln }}
        {{ students_choice_fn }}
        
        <input type="submit" value="select">
    </form>

    <br>
    <h4> {{ selected_student.first_name }} {{ selected_student.last_name }} </h4>

    {% if selected_student %}
        ....
    {% endif %}

  </div>
  <div class="col-md-6">
      ....
  </div>
</div>

</div>
</body>

{% endblock %}

The issue persists where only the second autocomplete dropdown functions, with the first dropdown displaying as an empty, non-responsive dropdown. Here is a screenshot for reference:

https://i.sstatic.net/tLEdK.png

Though there are threads discussing similar concepts, I was unable to find a solution for my specific problem:

How to use django-autocomplete-light on form with multiple charfields

https://github.com/yourlabs/django-autocomplete-light/issues/814

Your assistance is greatly appreciated!

Answer №1

Due to both forms being within the same form tag, they were assigned the same id in the final HTML output.

<form method=POST action="/awards/select">
    {% csrf_token %}
    
    {{ students_choice_ln }}
    {{ students_choice_fn }}
    
    <input type="submit" value="select">
</form>

Following the guidelines outlined in this documentation (https://docs.djangoproject.com/en/dev/ref/forms/api/#prefixes-for-forms), the dropdowns are now functioning correctly. The issue may have been caused by the conflicting ids affecting the behavior of the JavaScript and CSS links.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on scrolling the web page until the desired web element is visible and carrying out necessary tasks

When searching for input, multiple table data is retrieved. A "show as text link" is present in different table rows that needs to be clicked. I wrote a code that works fine in IE on one machine but does not work on a different machine due to variations i ...

Reading a JSON file using Javascript (JQuery)

Struggling to figure out how to handle a JSON file using JavaScript. Here are the details : { "streetCity": { "132":"Abergement-Clemenciat", "133":"Abergement-de-Varey", "134":"Amareins" } } I am attempting to access ...

Unleashing the potential of extracting the value of a subsequent iteration while within the

Currently, I am facing a dilemma as I am unable to comprehend the logic required to design this algorithm. The problem at hand involves a sequence of images with arrows placed alternatively between each image. The structure appears as follows: Image -> ...

Tips for resizing an image instead of a line in HTML5 canvas

For instance, we could create a function like this to draw a line: function drawLine(g, n, x1, y1, x2, y2){ g.beginPath(); g.lineWidth = n > 0 ? n : 1; g.strokeStyle = "rgb(0, 128, 32)"; g.moveTo(x1, y1); g.lineTo(x2, y2); g.str ...

Authentication Error (401) in WordPress JWT

Recently, I came across WordPress and started using it. However, I encountered some issues while trying to integrate JWT with a custom endpoint. Despite configuring my API and JWT correctly, I faced an authentication problem during my AJAX request. It&ap ...

Error encountered in clientside js file: Node.js indicates that 'require' is not defined

In my JavaScript file, I have important data that needs to be saved into a Mongoose schema and then inserted into a MongoDB table. The schema is stored in a separate directory, so I attempted to import it by adding the following line at the beginning of th ...

You cannot reassign NodeJS global variables

Currently, I am in the process of writing unit tests for code that utilizes a JavaScript library. This particular library sets a global variable if it does not already exist using the following pattern: var GLOBAL_VAR = GLOBAL_VAR || {} While this method ...

Connection error: API is down

The current issue I am facing with the application I'm developing is that it is not responding with the API address for weather data. Despite getting a response from Ajax, the specific weather API I am trying to call remains unresponsive. I have exha ...

What is the best way to trigger UseEffect when new data is received in a material table?

I was facing an issue with calling a function in the material table (https://github.com/mbrn/material-table) when new data is received. I attempted to solve it using the following code. useEffect(() => { console.log(ref.current.state.data); ...

Issue encountered while attempting to pass a function within the data in React

I've encountered an issue while trying to pass a function called sectionOne and then calling it from another component. The error message I received is quite confusing. Error: Warning: Functions are not valid as a React child. This may happen if you r ...

What is the best approach to comply with the EsLint rule "react-hooks/exhaustive-deps" and properly implement componentDidMount using hooks in React with a warning level?

After reviewing the React documentation, it appears that componentDidMount is now implemented using hooks as shown below: useEffect(() => { // your code here }, []) For example, if you wish to make an API call within this hook: useEffect(() => { ...

Is it possible to utilize JavaScript to access a .php file located in a separate directory?

Although I have been searching all day, I couldn't find a workout that specifically addresses my issue. I'm new to JavaScript and AJAX. Currently, I am exploring a web app called calendar.php located in the directory C:\xampp\htdocs&bs ...

Trouble with using .className for form validation

The .className is not applying the formValidation class on getWeight.length < 1 and getHeight.length < 1. I am stuck trying to figure out why this is happening after reviewing the code extensively. Any thoughts on what could be causing this issue? Y ...

Issue with AjaxComplete function failing to work

Currently, I am tackling the Opera workaround for printing IFrames. As we are aware, the only method to print an IFrame is by opening it in a new window and then printing it. However, I am encountering an issue where a series of ajax calls are triggered wh ...

Struggling with a Bootstrap v5.0.2 Modal glitch? Let's dive into a real-life case study to troub

I am seeking assistance with a problem that I am encountering. I am currently using Bootstrap version 5.0.2 (js and css). Despite coding all the required parameters, I am unable to make the modal functionality work. I have been trying to figure out what&ap ...

Troubleshooting sound problems in Angular JS

Can anyone help with pausing an AngularJS audio when the browser window is closed and resuming it when the window is maximized? I'm new to AngularJS and have no idea how to achieve this. var app=angular.module("myApp",['ngAudio']); ...

Creating a Union Type from a JavaScript Map in Typescript

I am struggling to create a union type based on the keys of a Map. Below is a simple example illustrating what I am attempting to achieve: const myMap = new Map ([ ['one', <IconOne/>], ['two', <IconTwo/>], ['three ...

Provide an identifier for the anchor tag

I need help passing an id that I am parsing from the url to an anchor tag. The code below shows how I am fetching the id from the url. For example, if the id is 123, then the anchor tag should be constructed like this- <a href="some_url&userId=123 ...

Determine if the webpage is the sole tab open in the current window

How can I determine if the current web page tab is the only one open in the window? Despite searching on Google for about 20 minutes, I couldn't find any relevant information. I would like to achieve this without relying on add-ons or plugins, but if ...

Showing Pictures on Django Form

How can I display an image within a Django form? My form is basic, with just one text input field. I want to pass the image path as a parameter when initializing the form in a view, so that when the form is rendered in the template, the image is also displ ...