Django autocomplete filter

Hi everyone,
I have a model class (InputSubsidy) in an app (input). This class has “farmInput”, “marketPrice”, “percentageSubsidy”, “startDate” and “endDate” fields. “farmInput” field is a foreign key from the FarmInput model app in the input app. Additionally, I have another class (InputRequestAuthorization) in an app(FarmManagement). InputRequestAuthorization has the fields “inputRequest”, “amountByCounty” and “amountByFarmer”. InputRequestAuthorization class inherits the InputSubsidy class. Both the InputRequest and InputSubsidy models have objects displayed in their respective admin interface. Since InputRequestAuthorization inherits the InputSubsidy class, on the admin interface, all the fields from InputSubsidy are displayed on the InputRequestAuthorization admin interface. I am using django and I want to auto-populate the InputSubsidy and InputRequestAuthorization models on the InputRequestAuthorization admin interface whn I click on one object item in the “farmInput” dropdown field. These fields include “marketPrice”, “percentageSubsidy”, “startDate”, “endDate”, “inputRequest”, “amountByCounty”, “amountByFarmer” fields in the InputRequestAuthorization class in the admin interface. There are multiple objects with the same value for farmInput. I will appreceiate any help on how to autocomplete these field values.

My files are:

class InputRequestAuthorization(InputSubsidy):
    inputRequest = models.ForeignKey(InputRequest, on_delete=models.CASCADE, verbose_name='Input Request')
    amountByCounty = models.SmallIntegerField(verbose_name='Amount by County')
    amountByFarmer = models.SmallIntegerField(verbose_name='Amount by Farmer')
    authorized= models.BooleanField()

    def __str__(self):
        return str(self.farmInput)

class InputSubsidy(models.Model):
    farmInput= models.ForeignKey(FarmInput, on_delete=models.CASCADE, verbose_name='Farm Input')
    marketPrice= models.SmallIntegerField(verbose_name='Market  price')
    percentageSubsidy=models.FloatField(max_length=100, verbose_name='Percentage Subsidy')
    startDate= models.DateField(verbose_name='Start Date')
    endDate= models.DateField(verbose_name='Start Date')

    class Meta:
        verbose_name= 'Input Subsidy'
        verbose_name_plural= 'Input Subsidies'

    def __str__(self):
        return str(self.farmInput)

Side note: When you post code here, please enclose the code between lines of three backtick - ` characters. This means you’ll have a line of ```, then the code, then another line of ```. This forces the forum software to keep your code properly formatted. (I’ve taken the liberty of editing your original post.)

Thank you. I didn’t know about the three backticks

The general pattern to implement something like this is to write a JavaScript function to catch the “change” event on the farmInput field, and pass that value to a new Django view. This view that you need to write will return the necessary values for the corresponding fields in the form. Your JavaScript function would then update the form with the data returned by the view.

(Note: This is pretty much the standard process for updating fields based upon a value entered in a different field. This isn’t a technique specific to the Django admin.)

I am using XMLHttpRequest to send a GET request to a new Django view . Then, passing the value of farmInput as a query parameter. The view will return a JSON object containing the necessary values for the corresponding fields in the form. The problem is that the value of form fields aren’t updating.

function updateForm() {
    var farmInput = document.getElementById("farmInput").value;
    var xhr = new XMLHttpRequest();"GET", "/get-input-data?farmInput=" + farmInput, true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            var data = JSON.parse(xhr.responseText);
            document.getElementById("marketPrice").value = data.marketPrice;
            document.getElementById("percentageSubsidy").value = data.percentageSubsidy;
            document.getElementById("startDate").value = data.startDate;
            document.getElementById("endDate").value = data.endDate;
            document.getElementById("inputRequest").value = data.inputRequest;
            document.getElementById("amountByCounty").value = data.amountByCounty;
            document.getElementById("amountByFarmer").value = data.amountByFarmer;

Here’s my view

from django.http import JsonResponse
from input.models import InputSubsidy

def get_input_data(request):
    farm_input = request.GET.get('farmInput')
    input_subsidy = InputSubsidy.objects.filter(farmInput=farm_input).first()
    if input_subsidy:
        data = {
            'marketPrice': input_subsidy.marketPrice,
            'percentageSubsidy': input_subsidy.percentageSubsidy,
            'startDate': input_subsidy.startDate,
            'endDate': input_subsidy.endDate,
        return JsonResponse(data)
        return JsonResponse({})

Check everything

Check the exchange of data in the browser’s developer tools network tab. Make sure the right url is being sent and that the response contains the right data.

Second, inspect the data being returned. Does data actually contain the object you’re expecting it to have?

Finally, verify that your updates should work by manually testing it in your browsers console. In other words, try something like:
document.getElementById("marketPrice").value = 5;
to see if the form has been updated. If it isn’t, then you may need to verify what the id attributes are of the form you’re trying to update.