this is the ajax code
$('.addtasksubmit').click(function(e) {
e.preventDefault();
$.ajax({
url: 'addtodo',
type: "POST",
data: {
title: $('#task-title').val(),
category: $('#catsel option:selected').val(),
'csrfmiddlewaretoken':$('input[name=csrfmiddlewaretoken]').val()
},
success: function(response) {
console.log(response)
$('.todos-box').append(`
<a href="#" >${response.category}</a>
`)
$("#addtodo").trigger('reset');
$("#exampleModal").modal('hide');
}
})
})
So ${response.category} gives me the id of the category but i need the category name to be viewed
and this is views.py
response = {
'title': request.POST['title'],
'category' : request.POST['category'],
}
todo = Todo.objects.create(title=response['title'],
category=Category.objects.get(id=response['category']),
user=request.user)
todo.save()
return JsonResponse(response, safe=False)
this is HTML
<select name="category" id="catsel">
<option seleted>Choose Category</option>
{% for category in categories %}
<option value="{{ category.id }}">{{ category }}</option>
{% endfor %}
</select>
is there any way to view the category name with ajax not the id? or how can i get the name of the category with its id.
sorry for my bad english..
CodePudding user response:
It would be helpful to get the HTML select input with the categories from the template. Based on what you posted please adjust the views.py to
todo = Todo.objects.create(title=response['title'],
category = Category.objects.get(id=response['category']),
user=request.user)
todo.save()
response = {
'title': request.POST['title'],
'category' : category.name,
}
return JsonResponse(response, safe=False)
CodePudding user response:
so i have solved his problem after 5 days of trying.
added this to the views
response['category']=Category.objects.filter(id=category)
.values('name').first()
data = json.dumps(response)
return HttpResponse(data)
and ajax
<div >
<a href="#" >${response['category'].name}</a>
</div>
and also added dataType: 'json'