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

发布于 2024-11-18 02:19:47 字数 437 浏览 0 评论 0原文

我正在使用这个

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 did not return an HttpResponse object

I am using this

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 ) )

I get this error

ajax_create didn't return an HttpResponse object

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

这个俗人 2024-11-25 02:19:47

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

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

Are you sure your request is an ajax call ? It doesn't look like it.
Try:

if request.is_ajax():
...
else:
  # If the request is not an ajax call, it will return a 400 Error.
  return HttpResponseBadRequest()
许久 2024-11-25 02:19:47

如果这是您的整个视图函数,也许 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))

Perhaps if request.is_ajax(): is returning False, if that's your entire view function?

Typically, you should follow this pattern when making Django view functions:

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))
素年丶 2024-11-25 02:19:47

它没有进入你的“如果”范围。它返回 None

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

检查您的 ajax 调用并确保它返回一些内容,以防请求不是阿贾克斯

It's not entering to your "if" scope. it returns None

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

Check your ajax call and make sure it returns something in case the request is not ajax

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文