首页 > 解决方案 > 在 Django 中将页面下载为 JSON

问题描述

我有一个返回格式化 JSON 对象的视图。它需要一个单词列表(在这个项目中标记为“表单”和“引理”),将它们格式化为一个漂亮的字典对象并输出一个 json 页面,然后用户可以保存该页面。

views.py

def search_view(request):
    """
    The app revolves around this view, which is also the homepage.
    """
    context = {}

    if request.method == 'GET':
        return render(request, 'search.html', context)

    if request.method == 'POST':
        checked_A = {}
        checked_B = {}

        # All lemma keys are of the form {lemma}@{group}.
        # All form keys are of the form {lemma}@{group}@{form}.
        # The "@" symbol will not appear in any other key.
        # Split the key_data into two parts, the lemma/group part
        # and the form part. The form part is either [] or [form]

        for key in request.POST:
            if "@" not in key:
                continue
            key_data = key.split("@")
            (lemma, group), form = key_data[:2], key_data[2:]
            if group == "A":
                if checked_A.get(lemma):
                    checked_A[lemma].extend(form)
                else:
                    checked_A[lemma] = list(form)
            if group == "B":
                if checked_B.get(lemma):
                    checked_B[lemma].extend(form)
                else:
                    checked_B[lemma] = list(form)

        context['query_A'] = checked_A
        context['query_B'] = checked_B

        return JsonResponse(context, status=200) # <-- the only important part

有没有办法创建一个按钮来直接下载这些数据,而不是让用户去一个单独的页面并保存数据?

标签: javascriptdjango

解决方案


要实现这一点,您必须简单地向 http 响应对象添加一个附加标头,特别是Content-Disposition: attachment标头。

在此处查看详细信息:https ://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition


推荐阅读