我现在在Django 1.7中看到了我可以使用该http.JSONResponse对象将JSON发送到客户端.我的观点是:
#Ajax
def get_chat(request):
usuario = request.GET.get('usuario_consultor', None)
usuario_chat = request.GET.get('usuario_chat', None)
mensajes = list(MensajeDirecto.objects.filter(Q(usuario_remitente = usuario, usuario_destinatario = usuario_chat) | Q(usuario_remitente = usuario_chat, usuario_destinatario = usuario)))
return JsonResponse(mensajes, safe=False)
Run Code Online (Sandbox Code Playgroud)
但我得到了下一个错误:
<MensajeDirecto:Towi CrisTowi>不是JSON可序列化的
你知道如何序列化QuerySet以JSON形式发回它吗?
我有Django的1.7版和Python版本2.7.5 - 我使用PIP安装simplejson和apt-get安装python-simplejson命令来解决这个问题,但它仍然显示我这个例外.Django和Python之间是否存在任何兼容性问题,或者解决此异常的解决方案是什么:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/root/test_env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/root/test_env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute
django.setup()
File "/root/test_env/local/lib/python2.7/site-packages/django/__init__.py", line 21, in setup
apps.populate(settings.INSTALLED_APPS)
File "/root/test_env/local/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate
app_config = AppConfig.create(entry)
File "/root/test_env/local/lib/python2.7/site-packages/django/apps/config.py", line 123, in create
import_module(entry)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/root/test_env/local/lib/python2.7/site-packages/extdirect.django-0.3-py2.7.egg/extdirect/django/__init__.py", line 3, in <module>
from providers import ExtRemotingProvider, ExtPollingProvider
File "/root/test_env/local/lib/python2.7/site-packages/extdirect.django-0.3-py2.7.egg/extdirect/django/providers.py", line 4, in <module>
from django.utils import simplejson …Run Code Online (Sandbox Code Playgroud) 我有一个django应用程序,它有html模板,我还有一个命令行python api,可以对服务器上的django应用程序执行GET和POST请求.api几乎可以完成django应用程序可以执行的所有操作.我怎么做到当我通过浏览器访问django应用程序时它返回html但是当我通过api访问它时它返回json?
我将在哪里放置json以及我必须对我的应用程序进行哪些更改?
谢谢
我有功能在视野中
from django.shortcuts import render
from .models import myModel
def articleTheme(request):
if request.method == 'POST':
article_id = request.POST['id']
article = myModel.objects.get(id=article_id)
theme = article.theme
return render(request, 'theme.html', {'newTheme': theme })
Run Code Online (Sandbox Code Playgroud)
现在它正常工作.但我有多余的HTML.我想要返回json对象.我可以导入和返回什么?