开发者

How to use Httpresponse in view in django while using Ajax

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 = Request开发者_如何学CContext( request ) )

I get this error

ajax_create didn't return an HttpResponse object


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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜