在temp中交流AJAX和Django视图

2024-05-16 10:41:50 发布

您现在位置:Python中文网/ 问答频道 /正文

你好,我正在尝试将我的视图与ajax脚本进行通信。在

urls.py

from .views import (
    video_testimonial,
)
urlpatterns = [
   url(r'^(?P<id>\d+)/video_testimonial/$', video_testimonial, name='video_testimonial'),
]

所以基本上它需要一个整数,这样url才能被访问。在

例如0/video_推荐/

这是我的

views.py

^{pr2}$

我的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();
^{4磅}$

错误显示: enter image description here


Tags: py脚本idurldatahtmlvideoajax
1条回答
网友
1楼 · 发布于 2024-05-16 10:41:50

与其使用.filter,不如使用.get,因为它应该返回一个对象。错误说明QuerySet不是Json可序列化的,这一点非常明显。你需要的是把对象转换成dict,这很容易做到

testimonial.__dict__

确保testimonial是模型对象而不是查询集。在

有关如何将对象转换为dict的详细信息,请检查https://stackoverflow.com/a/29088221/4117381

旁注:最好使用完整的url发出json请求。如果您使用的是Django模板,则可以使用{% url 'video_testimonial' id%}

相关问题 更多 >