Python 从Django获取JSON响应

Python 从Django获取JSON响应,python,json,django,dropzone.js,Python,Json,Django,Dropzone.js,编辑: 如前所述,我试图获得的东西如下: 使用视图中的“来自模板的文件-->文件”过程发布,生成一个id-->id显示在模板中 我是Django的新手,我正在尝试让服务器向同一页面发送一个响应,带有特定的数字。它当前正在响应ValueError,而模板没有得到响应。这是我的密码 views.py def index(request): dB = LegacyDatabase() ints = None if request.POST: form = UploadFileForm(requ

编辑: 如前所述,我试图获得的东西如下:

使用视图中的“来自模板的文件-->文件”过程发布,生成一个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")
url.py 从django.conf.url导入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>
你能帮帮我吗

编辑: 如所问,下面是开发服务器返回的错误

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
据我所见:

回溯在views.py的第66行中显示:

返回呈现(请求“main/index.html”,JsonResponse(sess))

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

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

编辑

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

您向它提供了一个
JsonResponse
。它是一个响应,它将包含请求的状态代码、标题和正文


因此,将
return JsonResponse(sess)
替换为
render(request,“main/index.html”,context=sess)
应该可以工作。

如果您遇到错误,应该将其与完整的回溯一起发布。不过,我想知道为什么您认为会有一个名为“file\u upload”的字段在POST数据中。模板中的Dropzone的名称。我的想法是POST数据引用了上传的文件,如果这不正确,请解释一下?不管是哪种方式,追踪都是后发的什么“Dropzone”?这是你第一次提到它。另外请注意,回溯的第十行显示错误发生在与您发布的代码不同的代码中。如果您不显示实际代码,我们可能无法帮助您。webapp应该从dropzone获取一个文件,将其上载到服务器,然后视图将处理文件名,在数据库中输入文件名和id,并将id作为json响应返回。错误现在已纠正。谢谢你在问题结构中的输入,我是新来的。谢谢。我已经用其他评论的反馈编辑了代码。现在是正确的,但是模板没有收到响应我不明白模板的哪一部分没有收到响应。也许你应该重新组织你的问题,增加更多的具体性。您是否正在尝试实现以下目标:获取请求-->模板-->显示空表单POST请求-->模板-->显示已发布的数据我已经编辑了帖子,请查看它是否已清除。然后将
if request.POST
替换为
if request.method='POST'
。然后在if循环内的返回中,执行而不是
returnjsonresponse(sess)
替换为
returnrender(请求,“main/index.html”,context=sess)
。检查我编辑的答案。
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