如何在使用Ajax时在django中使用Httpresponse

时间:2011-06-30 18:38:57

标签: ajax django django-views

我正在使用此

def ajax_create( request ):
    if request.is_ajax():

            form = SourceForm()

            template = 'ajax_form.html'
            data = {
                'form': form,
            }
            return render_to_response( template, data,
                context_instance = RequestContext( request ) )

我收到此错误

ajax_create didn't return an HttpResponse object

3 个答案:

答案 0 :(得分:2)

您确定您的请求是ajax电话吗?看起来不像。 尝试:

if request.is_ajax():
...
else:
  # If the request is not an ajax call, it will return a 400 Error.
  return HttpResponseBadRequest()

答案 1 :(得分:1)

如果那是你的整个视图函数,那么if request.is_ajax():可能会返回False吗?

通常,在制作Django视图函数时应遵循此模式:

def my_view(request):
    if request.method == 'POST':
        form = MyForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            # do something with form...
    else:
        initial = {...}
        form = MyForm(initial=initial)
    context = {'form':form, ...}
    return render_to_response('path/to/template.html', context, context_instance=RequestContext(request))

答案 2 :(得分:0)

它没有进入你的“if”范围。它返回无

https://docs.djangoproject.com/en/1.3/ref/request-response/#django.http.HttpRequest.is_ajax

检查你的ajax调用并确保它返回一些东西,以防请求不是ajax