Answer the question
In order to leave comments, you need to log in
How to find a bug in Django and Ajax interaction?
Hello.
I'm trying to make an updated select of models depending on the selected brand, but somewhere there is an error, I can't find it. That is, I do not get the brand_slug value from the POST request, if I write for example brand_slug = 'mazda', then everything will work.
viesws
@ensure_csrf_cookie
def ajax_get_mark(request):
brand_slug = request.POST.get('brand_slug', '')
marks = Mark.objects.filter(is_active=True, brand__slug=brand_slug)
t = get_template('ajax/filter-models.html')
response = t.render(Context({'marks': marks,}))
response = response.encode('utf-8')
return HttpResponse(json.dumps(response), content_type='application/json; charset=UTF-8',)
$('#brand').change(function(e) {
var brand_slug = $(this).find(':selected').val();
e.preventDefault();
$.ajax({
url: '{% url "seller.views.ajax_get_mark" %}',
type: 'POST',
data: {
'brand_slug' : brand_slug,
},
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (response, brand_slug) {
console.log(response, brand_slug);
// $('#mark').html(response);
},
error: function(){
alert("Ошибка запроса");
},
});
});
Answer the question
In order to leave comments, you need to log in
The reason for this is the string 'contentType: "application/json; charset=utf-8",'.
You send a djang post request with the body converted to json format. In request.POST, django puts only simple requests, that is, those that came in the format 'application/x-www-form-urlencoded'.
Remove this line and it should work.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question