简体   繁体   English

从 Django 获取 JSON 响应

[英]Getting a JSON Response from the Django

EDIT: As asked, the thing that I'm trying to obtain is the following:编辑:正如所问,我想要获得的东西如下:

POST with the file from template --> File process in the view, generate an id --> id displays in template使用模板中的文件进行POST --> 视图中的文件处理,生成一个id --> id 显示在模板中

I'm new to Django, and I'm trying to get the server to send a response to the same page, with a certain number.我是 Django 的新手,我试图让服务器向同一页面发送一个响应,并带有一定的数字。 It's currently responding with a ValueError, and the template doesn't get the response.它当前以 ValueError 响应,并且模板没有得到响应。 Here is my code.这是我的代码。

views.py视图.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 from django.conf.urls import url来自 django.conf.urls 的 urls.py 导入 url

from phast.views import index

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

index.html索引.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 %}'
});

Can you please help me?你能帮我么?

EDIT: As asked, here is the error that the development server returns.编辑:正如所问,这是开发服务器返回的错误。

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

By what I see:就我所见:

The trace back says in line 66 of views.py:回溯在 views.py 的第 66 行说:

return render(request, "main/index.html", JsonResponse(sess))返回渲染(请求,“main/index.html”,JsonResponse(sess))

This is the last line of your code and rest all are inbuilt of django.这是你的代码的最后一行,其余的都是 django 内置的。 So you should instead concentrate on this line.所以你应该把注意力集中在这条线上。

My approach would be to check the 66th line of views.py and debug whats going on there.我的方法是检查 views.py 的第 66 行并调试那里发生的事情。 If you don't see similar code in line 66 of views.py I bet you haven't restarted your django process.如果您在 views.py 的第 66 行没有看到类似的代码,我敢打赌您还没有重新启动 django 进程。 How are you running the server?你是如何运行服务器的? If any process is supervising it restart that process.如果有任何进程正在监督它,则重新启动该进程。

EDIT编辑

Template Context Django docs 模板上下文 Django 文档

If context is provided, it must be a dict.如果提供了上下文,则它必须是一个字典。 If it isn't provided, the engine will render the template with an empty context.如果未提供,引擎将使用空上下文呈现模板。

You were providing a JsonResponse to it.您正在为其提供JsonResponse It is a repsponse which will contain status code of the request, headers d body as well.这是一个包含请求的状态代码,headers d body 的响应。

so replacing return JsonResponse(sess) with render(request, "main/index.html", context=sess) should work.所以用render(request, "main/index.html", context=sess)替换return JsonResponse(sess) render(request, "main/index.html", context=sess)应该可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM