0

I am using django 1.4. I am moving codes from tornado to django. There is self.write() at the end of a class. What 's the alternative solution to self.write()? HttpResponse? There is only one template page so Do I need to response to other page? can I just call response? or render_to_response to the template page again to wrape data to the page? Is write() same with HttpResponse()? Hey, guys. there are many "?" above, But I only have one problem. An alternative solution of tornado's "write()" in django. thx for ur time.

The code in tornado looks like:

class DataHandler(tornado.web.RequestHandler):
    ...
    val = ...
    self.write(val)

Maybe in django?

def DataHandler(request):
    ...
    val = ...
    return HttpResponse(val)

Is that clear about my question?

Nick Dong
  • 3,638
  • 8
  • 47
  • 84

2 Answers2

1

HttpResponse is typically used if you wish to return non-template responses.

To render templates, use render from django.shortcuts, for example:

from django.shortcuts import render

def some_handler(request):
    context_for_template = {}
    return render(request, 'template_name.html', context_for_template)

From Tornado's documentation, write seems to be able to automatically convert a dictionary to JSON. HttpResponse does not do that by default, you should look at Creating a JSON response using Django and Python if it is part of your use case.

Community
  • 1
  • 1
Victor Neo
  • 3,042
  • 1
  • 17
  • 13
  • I am not gonna to return data to a template. I wish it can be return data to ajax. @Victor Neo "write()" also not return data to template, right? – Nick Dong Jan 28 '13 at 10:05
  • If you wish to return data to an Ajax request, then the link I gave on "JSON response using Django" will cover that use case, which uses a combination of HttpResponse and Python's json library. – Victor Neo Jan 28 '13 at 14:18
1

the HttpResponse module

from django.http import HttpResponse

def current_datetime(request):
    now = datetime.datetime.now()
    html = "<html><body>It is now %s.</body></html>" % now
    return HttpResponse(html)
mtt2p
  • 1,818
  • 1
  • 15
  • 22