简体   繁体   中英

Populate html element from selected dropdown value in Django

I am very new to django and AJAX and am trying to populate a HTML element (span for the time being) with data from a dropdown menu.

My current approach is to get the unique ID for the row through the id tag in the <option> element and post it with AJAX to views.py where that ID is then used as a filter in Django to GET the corresponding row. However, for some reason, whenever I try to filter the query nothing is returned. Whenever I remove the filter, all of the values are parsed, making me think that I'm getting the filter wrong somehow. I've tried many of the different filter types, but I just can't seem to get it right.

The HTML is:

<select id="drugSet">
{% for dose in dose_set %}
<option id="{{ dose.pubmed_id }}">{{ dose.drug_name }}</option>
{% endfor %}
</select>

<span id="drugName"></span>    
<a href="javascript:NeedDrugInformation()">Retrieve data</a>

The Javascript and AJAX are:

function NeedDrugInformation() {
        var elementID = document.getElementById("drugSet");
        var drugID = String(elementID.options[elementID.selectedIndex].id);

        $.ajax({
            type: "POST",
            url: "drugsanddoses/",
            dataType: "json",
            async: true,
            data: { csrfmiddlewaretoken: '{{ csrf_token }}', drugID: drugID },
            success : function(json) {
            },
            error : function(xhr,errmsg,err) {
            }
        });

        $.ajax({
            type: "GET",
            url: "drugsanddoses",
            dataType: "json",
            async: true,
            data: { csrfmiddlewaretoken: '{{ csrf_token }}' },
            success: function (json) {
                $('#drugName').html(json.drugInfo);
                // $('.ajaxProgress').hide();
            }
        })
    }

Views.py:

def drugsanddoses(request):

    drugID = request.POST.get('drugID')

    drugInfo = RiskCalculator.objects.filter(pubmed_id='drugID').values('drug_name', 'l_dose', 'h_dose', 'risk', 'pubmed_id', 'updated')    
    response_data = {}

    try:
        response_data['drugInfo'] = str(drugInfo)
    except: 
        response_data['result'] = 'No details found'
        response_data['message'] = 'There is currently no information in the database for this drug.'

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

As I said, I'm very new to this. Any pointers or ways I could be doing this better would be much appreciated.

First of all the POST field contains form posted values, not JSON. Parse Json payload first:

import json
drugID = json.loads(request.body).get('drugID')

Secondly you're using the string 'drugID' in your filter instead of the value in variable drugID . Try changing query line to:

drugInfo = RiskCalculator.objects.filter(pubmed_id=drugID).values('drug_name', 'l_dose', 'h_dose', 'risk', 'pubmed_id', 'updated')

You should also use a JsonResponse never catch all exceptions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM