在 Django 中从后端到前端操作和传递 JSON

时间:2021-02-15 17:54:23

标签: javascript python django

从我的数据库中,我是:

  • 获取我的用户发布的所有帖子。
  • 按从最新到最旧的顺序排列,然后......
  • 尝试将负载传递到 JSONResponse 中,以便我的前端 Javascript 可以处理它。

这个想法是,对于每个帖子,它都会显示一个包含数据的 DIV。

def allpoststest (request, posttype):

    if posttype == "allposts":
        allposts_ever = Post.objects.all()
        allposts_ever = allposts_ever.order_by("-timestamp").all()
        # Serialize the QuerySet into JSON (This strings it)
        json_data = serializers.serialize("json", allposts_ever)
        # DeString it the data into JSON data (LIST)
        json_data = json.loads(json_data)
        # Try to turn list into numpy.ndarray
        json_data = np.array(json_data)
        # Context it
        context = {'json_data': json_data}
        # Pass the JSON formatted data to the Front End
        return JsonResponse(context, safe=False)

document.addEventListener('DOMContentLoaded', function() {

    document.querySelector('#trigger').addEventListener('click', () => load_allposts('allposts'));


})

function load_allposts(posttype) {

    fetch(`/test/${posttype}`)
        .then(response => response.json())
        .then(response => console.log(response))
        .then(json_data => {
            console.log(json_data);

            json_data.forEach(post => {
    
                const div = document.createElement("div");
    
                div.innerHTML =
                `
                <div class="card" style="width: 100%;">
                <div class="card-body">
                    <h5 class="card-title">Posted by ${ post.user }</h5>
                    <h6 class="card-subtitle mb-2 text-muted">Posted on ${ post.timestamp }</h6>
                    <p class="card-text" style="text-align: center;">${ post.post }</p>
                    <div class="btn-toolbar" role="toolbar" aria-label="Toolbar with button groups">
                        <div class="btn-group mr-2" role="group" aria-label="First group">
                            <button id="likebtn" class="btn btn-info" type="button">Like</button>
                            <button id="unlikebtn" class="btn btn-info" type="button">Unlike</button>
                            <button id="likecount" class="btn btn-info disabled" type="button">0</button>
                        </div>
                        <div class="btn-group mr-2 btn-group-sm" role="group" aria-label="Second group"> 
                            <button id="editbtn" class="btn btn-secondary mr-2" type="button">Edit</button>
                            <button id="deletebtn" class="btn btn-danger" type="button">Delete</button>
                        </div>
                    </div>
                </div>
                </div>
                `
                document.querySelector('#allposts-view').append(div);
            })   
        })
}
  1. 你能帮助大大简化 python 代码吗?虽然我的理解是序列化 QuerySet 然后在前端将它传递给 JSONify 它应该可以工作,但它没有。

我认为没有必要将 QuerySet > Serialize > Destringfy > 从 List 更改为 Array。

  1. Javascript 本身似乎正确加载,因为我可以在单击 div“id=trigger”时触发我的函数,但是,使用上面的代码,我获得:
XHRGEThttp://127.0.0.1:8000/test/allposts
[HTTP/1.1 500 Internal Server Error 34ms]

Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

我很高兴将 fetch(/test/${posttype}) 编辑为 fetch(/test),因为这会删除 XHR 错误。但我仍然有解析问题。

希望能帮到你!

2 个答案:

答案 0 :(得分:1)

这对你有用吗?

def allpoststest (request, posttype):
    if posttype == "allposts":
        allposts_ever = Post.objects.all()
        allposts_ever = allposts_ever.order_by("-timestamp").all().values()
        allposts_list = list(allposts_ever)
        return JsonResponse(allposts_list, safe=False)

答案 1 :(得分:0)

需要简单地获取 list(QuerySets.values()) 并将其传递给前端,如下所示:

def allpoststest (request, posttype):

    allposts_ever = Post.objects.all()
    allposts_ever = allposts_ever.order_by("-timestamp").all().values()
    allposts_list = list(allposts_ever)
    return JsonResponse(allposts_list, safe=False)

然后前端可以处理“JSON List”,解析它(.json())并处理它:

function load_allposts(posttype) {

    fetch(`/test/${posttype}`)
        .then(response => response.json())
        .then(allposts_list => {
            
        console.log(allposts_list);
}
相关问题