【问题标题】:Django don't want to include the whole template in the HttpResponseDjango 不想在 HttpResponse 中包含整个模板
【发布时间】:2014-03-26 08:10:45
【问题描述】:

我有一个这样的视图函数:

from django.http import Http404, HttpResponse
from django.template import Context, loader

from .models import Recipe


def index(request):
    recipes = Recipe.objects.all()
    t = loader.get_template('recipes/index.html')
    c = Context({'object_list': recipes})
    return HttpResponse(t.render(c))

但是因为我想实现一些 AJAX,所以我不想在 HttpResponse 对象中包含整个呈现的模板,而只需要将所需的数据传递给 AJAX 成功函数。

我的问题是:如何让我的视图函数在响应中只返回 ajax 所需的数据,而不需要包含整个模板(就像现在一样)

【问题讨论】:

  • ajax响应是否需要返回html或者xml/json等其他格式?
  • 为了简单起见,我只想以任何格式传递 AJAX 成功响应所需的数据。我不想传递整个 html 模板并在查找所需数据后,我认为这不是最合适的方式
  • “所需数据”需要采用什么格式,html 还是 xml/json?解决方案取决于这个答案。
  • 我希望使用任何格式,但如果这不可能,我想我会使用 json。谢谢

标签: ajax django django-views


【解决方案1】:

如果你想发送 json 响应。你可以这样做。

from django.core import serializers


def index(request):
    recipes = Recipe.objects.all()
    data = serializers.serialize('json', recipes)
    return HttpResponse(data, content_type='application/json')

【讨论】:

  • 在这种情况下,哪个 html 模板将加载视图?
  • 它将 json 响应返回给您的 ajax 调用。
猜你喜欢
  • 2017-05-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-17
  • 2013-04-26
  • 2017-09-28
  • 2018-02-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多