Auto-filling a form with the selected 'id' in Django using JavaScript or AJAX

I am a novice and I want the form to be autofilled when I select a vehicle ID from the template. Here are my models.

class Fuel(models.Model):
vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE)
previous_km = models.IntegerField(blank=False, null=False)
progressive_km = models.IntegerField(blank=False, null=False)

When I choose a vehicle, the corresponding vehicle's previous_km is automatically populated in the form. I have manually written a simple JavaScript code for this but I wish to fetch it from the database.

<script>
let usersData = [
    {
        id: 1,
        email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ef9adeaf88828e8683c18c8082">[email protected]</a>",
        fname: "fname-1",
        lname: "lname-1",
        previous_km : 1000,
    },
    {
        id: 2,
        email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="10652250777d71797c3e737f7d">[email protected]</a>",
        fname: "fname-2",
        lname: "lname-2",
        previous_km : 2000,
    },

];
document.getElementById('vehicle').onchange = (e) => {
    let selectedUser = usersData.find(userdata => userdata.id == e.target.value);
    console.log(selectedUser);
    document.getElementById('previous_km').value = selectedUser.previous_km;

};

Answer №1

This is my typical approach, utilizing JQuery + Ajax for handling the submission process.

Javascript (JQuery)

$(document).ready(function() {
    $("#vehicle").change(function(){
        if ($(this).val() == ''){
            // value is blank, do not proceed with posting
            return;
        };

        postdata = {
            'vehicle_pk': $(this).val(),

            // token for authentication when logged in
            'csrfmiddlewaretoken': $('[name=csrfmiddlewaretoken]').val(),
            //  This needs to be in template: {% csrf_token %}
        };

            
        $.ajax({
            method: 'post',
            url: 'url_to_view', // insert your URL here
            data: data,
            beforeSend: function(){
              $('#ajaxSendingDiv').fadeIn().attr({'reload':1});
            },
            success: function(data){
                console.log(data);
                if (data['status']){
                    $('#previous_km').val(data['previous_km']);
                    // perform action
                }else{
                    alert(data['msg']);
                };
            },
            error: function(event,xhr,settings,errorText){
                //xhr.status general meanings:
                // 0    = Server didn't Reply (server down)
                // 400  = Bad Request         (Syntax Error)
                // 403  = Forbidden           (Login Token Expired)
                // 403  = Not Found           (Invalid Url)
                // 500  = Server Error        (Django Crash)
            },
        });
    });
};

View.py (general)

def GetPrevKM(request):
    if request.method == 'POST':
        data = {'status':False}

        # perform query and retrieve data..
        #   Not completely sure about your model setup
        #       but this is the basic format
        obj = Fuel.objects.filter(pk=request.POST.get('vehicle_pk'))
        if obj:
            data['status'] = True
            data['previous_km'] = obj.previous_km
            data['progressive_km'] = obj.progressive_km
            data['msg'] = 'Returned Fuel Information'
        else:
            data['msg'] = 'No Fuel found on row: {0}'.format(request.POST.get('vehicle_pk'))

        import json
        return HttpResponse(
            json.dumps(data),
            content_type="application/json"
        )

    # Post only View!
    from django.http import Http404
    raise Http404

I suggest exploring JQuery further as it can greatly enhance productivity (in my opinion) and is widely utilized for tasks like this.

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

Divide the sentence using unique symbols to break it into individual words, while also maintaining

Is there a way to split a sentence with special characters into words while keeping the spaces? For example: "la sílaba tónica es la penúltima".split(...regex...) to: ["la ", "sílaba ", "tónica ", "es ", "la ", "penúltima"] ↑ ...

What is the best way to send information to a component using Props in Vue2?

Recently, I created a .Vue file to showcase information about a cafe on the Cafe Details Page. However, to streamline template updates, I decided to extract certain parts of this details page and turn it into its own component. This led me to create a new ...

What methods are available for retrieving specific XML entries using JavaScript?

Hey there, I'm dealing with this XML code <book> <bookname>book1</bookname> <author>authorman</author> </book> <book> <bookname>book2</bookname> <author>authorperson</author> </book ...

Guide to verify the user selection within a select form

Here is a form with a select field: <form method="post" name="posting_txt" onSubmit="return blank_post_check();" id="post_txt"> <select style="background: transparent; border-bottom:5px;" name="subname" class="required"> ...

Sockets causing a blockage in the Express server

Encountering an issue while setting up an express server with Sockets (using the socketcluster-server module). After sending around 20 http requests, the express server gets blocked, leading to the Sockets (client) reporting a connection depletion. Has an ...

Display the text area when the "Yes" radio button is clicked, while it remains hidden either by default or when the "No" radio button is selected

I am currently working on an html code and I am looking for a way to use java script in order to create a text area box only when the "Yes" radio button is selected. This text area should be hidden by default or when selecting "NO". <table class="tab ...

Displaying search results in various Angular components

On my home page (homePageComponent), I have a search feature. When the user clicks on the search button, they are redirected to a different page called the search list page (searchListComponent). Within the searchListComponent, there is another component c ...

Emphasizing the date variable within a spreadsheet

Hey there! I'm struggling with the code below: <html> <head> <title>highlight date</title> <style> .row { background-color: Yellow; color:blue; } </style> <script type="text/javascript"> </script> &l ...

switch between showing and hiding dynamic table rows

As I dynamically add rows to a table, each row can either be a parent row or a child row. My goal is to toggle the visibility of child rows when the parent row is clicked. if (response != null && response != "") { ...

What is causing the sorting table to fail in React when using useState?

import React, { useState } from "react"; import "./App.css"; const App = () => { const [data, setData] = useState([ { rank: 1, name: "John", age: 29, job: "Web developer", }, { rank: 2, name: "Micha ...

Tips for adjusting column sizes in ag-grid

I'm a beginner with ag-grid and need some help. In the screenshot provided, I have 4 columns initially. However, once I remove column 3 (test3), there is empty space on the right indicating that a column is missing. How can I make sure that when a col ...

The coordinates of the event do not match the coordinates of the location. Successful AJAX response data

How can I retrieve the accurate latitude and longitude when the Google Maps marker finishes dragging? It's confusing because for the same exact point, two different (but very approximate) coordinates are provided. Here are some example results for t ...

What is the best way to import a TypeScript file in index.js?

I've recently developed an application using the react-express-starter template. I have a "server" directory where the backend is created by nodejs, containing an index.js file: const express = require('express'); const app = express(); c ...

Unable to establish a connection with Metamask

Looking to connect to Metamask and retrieve the account balance: <!DOCTYPE html> <html> <head> <title>Testing Ethereum with Metamask</title> <meta charset="UTF-8"> <meta name=&quo ...

What is the best way to access attributes from a div element?

I am currently working on extracting attributes from within a div tag, specifically the custom attributes of the first child element. I am using web scraping techniques with Node.js and Puppeteer. My goal is to retrieve the custom attributes data-ticker, d ...

The process of passing $refs in Vue explained

I have a feature where all the data is passed to the child component. Currently, I am able to pass $attrs and $listeners successfully: <template> <el-form v-on="$listeners" v-bind="$attrs" :label-position="labelPosition"> <slot /> ...

What is the reason for Jest attempting to resolve all components in my index.ts file?

Having a bit of trouble while using Jest (with Enzyme) to test my Typescript-React project due to an issue with an alias module. The module is being found correctly, but I believe the problem may lie in the structure of one of my files. In my jest.config ...

"Enhancing User Experience with AngularJS by Dynamically Modifying and Refresh

I'm currently attempting to dynamically add HTML elements using JavaScript with a directive: document.getElementsByClassName("day-grid")[0].innerHTML = "<div ng-uc-day-event></div>"; or var ele = document.createElement("div"); ele.setAttr ...

Real-time functionality is not supported by Firebase functions

I've set up a firebase query within a method in VueJS: data: {this.todaysEvents}, methods : { getTodaysEvents (day) { this.todaysEvents = [] const events = db.ref('calendar') const query = events.orderByChild('da ...

The resolution of Angular 8 resolver remains unresolved

I tried using console.log in both the constructor and ngOnInit() of Resolver but for some reason, they are not being logged. resolve:{serverResolver:ServerResolverDynamicDataService}}, console.log("ServerResolverDynamicDataService constructor"); console ...