问题
I'm trying to make a tagging system in Django. Basically I'm passing through a list of tags (checkboxes in a form) through AJAX to a Django view which will update the list of tags with a new selection of relevant tags in an httpresponse.
The problem is that Django only seems to be receiving the last element of the list on its own even after getlist. In fact, if I print the entire request.GET, it shows just one element in each list.
The javascript/jQuery code is here:
$(document).on('change', '.form-check-input',function () {
var all_tags = $("input:checkbox").map(function() { return this.id; }).get();
var selected_tags = $("input:checkbox:checked").map(function() { return this.id; }).get();
alert(all_tags);
alert(selected_tags);
$.ajax({
url: "{% url 'AJAX_tagFilter' %}",
data: { 'all_tags': all_tags, 'selected_tags': selected_tags },
cache: false,
type: 'GET',
success: function (data) {
alert(selected_tags);
$('#test').html(data);
console.log('success');
}
});
});
And I did a couple of alerts so that I can see what is being passed is correct at each stage. I see all the tags I expect it to.
12,13,21,16,17,15,11,7,18
12,13
But when it gets to the Django view:
def getTagFilterSidebar(request):
if 'selected_tags[]' in request.GET:
all_tags = request.GET.getlist("all_tags[]")
selected_tags = request.GET.getlist("selected_tags[]")
debug_text4 = str(request.GET)
I don't see the list of tags. This is the output:
<QueryDict: {'_': ['1539460657253'], 'all_tags[]': ['18'], 'selected_tags[]': ['13']}>
The critical part of this is that it seems to run fine on my local server. However, I'm using Zappa and have uploaded it to AWS. It's only on AWS that it isn't working right. So I'm a little puzzled as to what's happening. I'd really appreciate some help, thanks!
回答1:
The problem is that jQuery is serializing the array by using duplicate query parameters, something that Amazon API Gateway (used by Zappa) doesn't support.
Or didn't, I should say. Just a few days ago Amazon announced that API Gateway will now support this:
Starting today, Amazon API Gateway supports multiple headers and query string parameters with the same name in the API Request.
In any case, as you've discovered, you can just implement your own serialization that doesn't require duplicate query parameters.
回答2:
As suggested by Daniel Roseman:
Instead of passing a list, I used the join function in the two variables into a comma delineated string:
var all_tags = $("input:checkbox").map(function() { return this.id; }).get();
var selected_tags = $("input:checkbox:checked").map(function() { return this.id; }).get();
From there, I used the split function in Django to reverse the process:
all_tags = request.GET.getlist("all_tags")[0].split(",")
Not the most direct way of solving the problem, but quick and easy.
来源:https://stackoverflow.com/questions/52796932/django-ajax-request-only-getting-last-element-not-getlist-issue