Django 在请求后返回 None.发布

Django returning None after request.POST.get

本文关键字:None 发布 返回 请求 Django      更新时间:2023-09-26

我是Django和AJAX的新手,我正在尝试使用ajax POST将下拉列表的ID发送到Django View。然后,在查询集筛选器中使用此 ID,以根据 ID 使用 AJAX 返回行。我陷入了将过滤器应用于查询集的问题,因为它似乎发布了 ID,然后发布了一个带有 None 的变量。当我打印控制台以控制台在 POST 中发送的变量时,我得到 ID,后跟 none,例如:

1748
None

我的HTML是:

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

Javascript:

function NeedDrugInformation() {
            var elementID = document.getElementById("drugSet");
            var strUser = elementID.options[elementID.selectedIndex].id;
            $.ajax({
                type: "POST",
                url: "drugsanddoses/",
                dataType: "text",
                async: true,
                data: { csrfmiddlewaretoken: '{{ csrf_token }}', drugID: strUser },
            });
            $.ajax({
                type: "GET",
                url: "drugsanddoses",
                dataType: "text",
                async: true,
                data: { csrfmiddlewaretoken: '{{ csrf_token }}' },
                success: function (json) {
                    $('#drugName').html(json.drugInfo);
                    // $('.ajaxProgress').hide();
                }
            })
        }

views.py:

def drugsanddoses(request):
    drugIdentifier = request.POST.get('drugID')
    print(drugIdentifier)
    drugInfo = RiskCalculator.objects.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")

您正在发出两个 Ajax 请求;一个是 POST,其中存在 ID,另一个是 GET,其中 ID 不存在,因此它打印 None。我真的不明白你为什么要提出两个要求,但这就是你正在做的事情。