简体   繁体   English

Django在request.POST.get之后返回None

[英]Django returning None after request.POST.get

I'm new to Django and AJAX and I'm trying to send the ID of a dropdown list to the Django View with an ajax POST. 我是Django和AJAX的新手,并且尝试使用ajax POST将下拉列表的ID发送到Django View。 This ID is then used in a queryset filter to return with AJAX the row, based off the ID. 然后,此ID在查询集过滤器中使用,以基于ID从AJAX返回该行。 I'm getting stuck with applying the filter to the query set, as it seems to be posting the ID and then a variable with None. 我陷入了将过滤器应用于查询集的困境,因为它似乎正在发布ID,然后发布一个无值的变量。 When I print to console the variable sent in the POST I get the ID, followed by none, eg: 当我打印以控制台发送在POST中发送的变量时,我得到了ID,然后没有ID,例如:

1748
None

My HTML is: 我的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: 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: 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")

You're making two Ajax requests; 您正在发出两个Ajax请求; one a POST, where the ID is present, and one a GET, where the ID is absent so it prints None. 一种是POST(其中存在ID),另一种是GET(缺少ID),因此它显示None。 I don't really understand why you're making two requests, but that is what you are doing. 我真的不明白您为什么要提出两个请求,但这就是您正在做的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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