Reputation: 471
Hello I am trying to communicate my view to my ajax script.
urls.py
from .views import (
video_testimonial,
)
urlpatterns = [
url(r'^(?P<id>\d+)/video_testimonial/$', video_testimonial, name='video_testimonial'),
]
So basically it requires an integer in order the url can be access.
e.g 0/video_testimonial/
Here's my
views.py
def video_testimonial(request, id):
testimonial = Testimonial.objects.filter(id=id)
if request.is_ajax():
context = {
'testimonial': testimonial,
}
return JsonResponse(context)
else:
raise Http404
my script (internal script) in my html:
presentation.html
function showVideoTestimonial() {
var id = parseInt($('.carousel-inner a').attr('id'));
$.ajax({
url: id +'/video_testimonial/',
success: function (data) {
console.log(data.testimonial);
$('.carousel-inner a').click(function () {
console.log(id);
});
}
})
}
showVideoTestimonial();
url: id +'/video_testimonial/', am i missing something accessing the url? thanks for responding
Upvotes: 0
Views: 338
Reputation: 1172
Rather than using .filter
, you should use .get
as it should return one object. The error says that the QuerySet is not Json serializable which is very obvious. What you need is to just convert the object to dict. It can easily be done by doing
testimonial.__dict__
Make sure that testimonial
is a model object not a queryset.
For more details how to convert the object to dict you can check https://stackoverflow.com/a/29088221/4117381
Side Note: It is always better to make the json request with the full url. If you are using Django template you can use {% url 'video_testimonial' id%}
Upvotes: 1