从Django获取JSON响应

时间:2017-02-01 18:17:30

标签: python json django dropzone.js

编辑: 如我所知,我试图获得的是以下内容:

使用模板中的文件进行POST - >文件在视图中处理,生成一个id - > id显示在模板中

我是Django的新手,我试图让服务器向同一页面发送一个具有一定数量的响应。它目前正在使用ValueError进行响应,模板没有得到响应。这是我的代码。

views.py

def index(request):
dB = LegacyDatabase()
ints = None
if request.POST:
    form = UploadFileForm(request.POST, request.FILES)
    if form.is_valid():
        files = Upload(model=request.FILES['file_upload'])
        try:
            ints = dBconnection(dB, request.FILES['file_upload'].name)
        except IntegrityError:
            ints = dBGetExistingValue(dB, request.FILES['file_upload'].name)
        files.save()
        a = []
        a.append(["sessionid", ints])
        sess= dict(a)

        return JsonResponse(sess)
return render(request, "main/index.html")

urls.py     来自django.conf.urls import url

from phast.views import index

urlpatterns = [
  url(r'^$', index, name='main'),
]

的index.html

   <form method="post" class = "sessionid">
    <input type="text" id = "demo" readonly>
  </form>
  <script>

    var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
      console.log(JSON.parse(xhttp.responseText));
      }
    };
  </script>

 <form class="dropzone" id="mydropzone" enctype="multipart/form-data">  {% csrf_token %} </form>

dropzone creation

var myDropzone = new Dropzone("#mydropzone", {
  url : '{% url phast.views.index %}'
});

你能帮帮我吗?

编辑: 如上所述,这是开发服务器返回的错误。

Internal Server Error: /
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py", line 39, in inner
    response = get_response(request)
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/rubinhus/Development/django/phastload/phast/views.py", line 66, in index
    return render(request, "main/index.html", JsonResponse(sess))
  File "/usr/local/lib/python2.7/dist-packages/django/shortcuts.py", line 30, in render
    content = loader.render_to_string(template_name, context, request, using=using)
  File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py", line 68, in render_to_string
    return template.render(context, request)
  File "/usr/local/lib/python2.7/dist-packages/django/template/backends/django.py", line 64, in render
    context = make_context(context, request, autoescape=self.backend.engine.autoescape)
  File "/usr/local/lib/python2.7/dist-packages/django/template/context.py", line 267, in make_context
    context.push(original_context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/context.py", line 59, in push
    return ContextDict(self, *dicts, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/template/context.py", line 18, in __init__
    super(ContextDict, self).__init__(*args, **kwargs)
ValueError: dictionary update sequence element #0 has length 19; 2 is required

1 个答案:

答案 0 :(得分:0)

我所看到的:

回溯在views.py的第66行中说明。

  

return render(request,&#34; main / index.html&#34;,JsonResponse(sess))

这是你的代码的最后一行,所有内容都是django内置的。所以你应该专注于这一行。

我的方法是检查第66行views.py并调试那里发生的事情。如果您没有在views.py的第66行中看到类似的代码,我打赌您还没有重新启动您的django进程。你是如何运行服务器的?如果任何进程正在监督,则重新启动该进程。

修改

Template Context Django docs

  

如果提供上下文,则必须是dict。如果未提供,则引擎将使用空上下文呈现模板。

您正在向其提供JsonResponse。这是一个repsponse,它将包含请求的状态代码,标题也是正文。

所以用return JsonResponse(sess)替换render(request, "main/index.html", context=sess)应该有用。