Using JavaScript onChange event with ModelChoiceField arguments

In my Django project, I have a Students model with various fields. I created a ModelChoiceField form allowing users to select a record from the Students table via a dropdown.

forms.py:

class StudentChoiceField(forms.Form):

    students = forms.ModelChoiceField(
        queryset=Student.objects.values_list().order_by("last_name"),
        empty_label="(select student)",
        widget=forms.Select(attrs={"onChange":'refresh()'})
    )

    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)

To display just two selected model fields in the dropdown, I customized the label_from_instance method even though there are 11 total model fields.

Upon selecting a student, I aim to update textfields on the page with the rest of the model's fields. I've implemented a Javascript function called refresh(), triggered by onChange event of the StudentChoiceField form.

index.html (all_students_choice references the StudentChoiceField form):

{% extends "base.html" %}

{% block content %}

<body>

<script>
    function refresh(){
        var id = document.getElementById("id_students").value;
        console.log(id);
    }
</script>

<div class="container">
    <form method=POST action="">
        {% csrf_token %}
        {{ all_students_choice }}
    </form>
</div>

</body>

{% endblock %}

After testing in the browser console and verifying that the function properly retrieves the value of the ModelChoiceField form upon selection, I now seek advice on how to populate additional textfields on the page with the remaining Student model fields (excluding first and last name). Should these be passed as parameters to the Javascript function, or is there a better approach?

Answer №1

Responding to this query by explaining the approach that was ultimately used, in case it might benefit others. Opted to modify the template slightly by introducing an extra element in the context to identify the chosen student. Initially, on the home page index, the selected_student variable is set to None:

def index(request):
    ....  

    context = {
        'students_choice_ln': students_choice_ln,
        'students_choice_fn': students_choice_fn,
        'selected_student': None
    }

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

In the select function, the selected_student value is passed through the context:

def select(request):
    if request.method == "GET":
        ...
        student_id = ...
        selected_student = Student.objects.get(pk=student_id)
        ...

        context = {
            ...
            'students_choice_ln': students_choice_ln,
            'students_choice_fn': students_choice_fn,
            'selected_student': selected_student,
            ...
        }

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

The template can then determine if the selected_student variable exists or not, and display additional fields accordingly in a separate section.

If any seasoned web developers / django developers notice any issues with this setup, feel free to offer insights.

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

Is it possible to access the ID of a collection_select and have a list of items appear whenever the selection is modified?

I am working on a form named _form.html.erb <%= simple_form_for(@exam) do |f| %> <%= f.error_notification %> <div class="field"> <%= f.label :Year %> <%= f.collection_select :year_id, Year.order(:name), :id, :name, ...

Using Jquery selectors along with variables to perform targeted search operations

I need assistance creating a JQuery selector that can automatically add an active class to a specific list item based on a variable. The variable sv will hold either 'dom-site' or 'int-site', which correspond to the id of a list item i ...

The conceal feature doesn't appear to be functioning properly on jQuery Mobile

I am facing an issue with a small mobile app built using jQuery Mobile. Within a div, I have three buttons and other content. My goal is to hide these three buttons if the user's device is running on Windows (WP). The buttons are defined as follows: ...

Is there a way to create a self-contained installation package for my Vue application?

Is it possible for my application to be downloaded and installed without requiring internet access after the download is complete? I am looking to create a standalone installer for this purpose. Are there any suggestions on how to go about implementing t ...

Troubleshoot: React and Laravel login authentication issues

I am relatively new to working with React, React Router, and Laravel for authentication. I've been trying to set up authentication using Laravel, React, and React Router, and although the page redirects to the desired destination when the submit butto ...

confirm that the form is necessary and contains text

How can I ensure that a specific text string is validated for the input field labeled "promo"? Take a look at the code snippet below: <script> function validateForm() { var x = document.forms["myInquiry"]["promo"].value; if (x == null || x == "") ...

Display modal within a React list

I need to display a list of items with an edit button for each item, which should trigger a modal showing the details of that specific item. Initially, I had a single modal component in the parent element and passing the visible values to the parent state ...

There seems to be an issue with [object%20Object]/undefined within the

AuthenticationService.js import axios from 'axios'; const AUTH_API_BASE_URL = "http://localhost:8087/auth"; class AuthenticationService { login(user) { return axios.post(AUTH_API_BASE_URL + "/login", user); } getRo ...

What is the best way to determine the normals of a closed shape in three.js?

I am currently developing a custom mesh importer for my proprietary file format. The challenge I'm facing is that the format does not include normal data. As a result, I am exploring methods to calculate normals for enclosed shapes and then apply thos ...

Modifying the input placeholder color with ng-style

I am working on setting the color of my input placeholder using a dynamic color defined in a $scope variable in my controller for my HTML code. The $scope variable is structured as follows: $scope.primaryColor={"color":colorVar}; //colorVar represents th ...

Issue with iframe's size not displaying correctly

<body> <script> document.write("<iframe id='theframe' src='http://www.website.com?testvr=" + testvr + " height='900' width='500'></iframe>"); </script> </body> The iframe is added, but ...

Error: The function user.comparePassword does not exist or is not defined

I am facing an error that says TypeError: user.comparePassword is not a function. I have ensured that all dependencies are installed and the APP is linked to all the libraries. I tried using Postman to retrieve data, but it doesn't seem to be workin ...

Modifying the 'objects' attribute of a superclass in Django without altering the superclass code

Within my code, I have defined two classes: class Parent(models.Model) # class definition The second class is as follows: class Child(models.Manager): def get_queryset(self): pass My goal is to override the 'objects' of the Pa ...

Identify specific elements using CSS to easily target them with JavaScript later on

Currently, I am utilizing CSS selectors to target specific elements and now I want to be able to identify those elements using javascript. My approach involves setting the color of these elements in css and then retrieving them based on their color. Howeve ...

Leveraging JSON in conjunction with AJAX and Python database operations

I am a beginner in Python and I am attempting to access the database through Python in order to retrieve results in a JSON array using AJAX. When I test it by returning a JSON list and triggering an alert in JavaScript, everything works fine. However, as ...

The error message "POST .../wp-admin/admin-ajax.php net::ERR_CONNECTION_CLOSED" appears when a WordPress AJAX request receives data that exceeds 1MB in size

When I attempt to submit a jquery ajax form from the frontend and upload a blob (a variable of string) as a .txt file to WordPress using wp_handle_upload(), everything works smoothly until the file size reaches around 1mb. At that point, an error is displa ...

Trigger the onClick event of an element only if it was not clicked on specific child elements

<div onClick={()=>do_stuff()}> <div classname="div-1"></div> <div classname="div-2"></div> <div classname="div-3"></div> <div classname="div-4"></div> ...

Using Angular to dynamically access component properties

Seeking assistance with creating dynamic Tabs in TabView of PrimeNG. The components are displaying properly, but I am unsure how to access their properties. I am following the guidelines provided at https://angular.io/guide/dynamic-component-loader and us ...

Advancement in the Web API Controller procedure

I am currently working on an ASP.NET web form that allows users to select a mailing list and send emails to all members of the list by clicking the Send button. When the user clicks the button, I trigger an Ajax call to an ASP.NET Web API method which then ...

Error thrown due to obtaining multiple objects using the `get_or_create` method

Here is a concise snippet of code I have for retrieving or creating a conversation for the current user: c, created = Conversation.objects.get_or_create( message__sender=request.user, content_type=get_content_type(request.POST['ct']), ...