user1767962
user1767962

Reputation: 2109

django - render to response from function - not working

I have a view like this :

  def myview(request):
      print "A"

      some_function()

      return HttpResponse("This should not appear")

  def some_function():
      return render_to_response("templ.html", {}, context_instance=RequestContext(request))

Here, the function renders template if i call the function like this :

    return some_function()

But it always expect the function to return, but i want the function to return only at certain times. I can use some logic in the view whether to return or not, but i am asking it is possible to do everything in the view so i can simply call the function ?

Upvotes: 0

Views: 396

Answers (1)

bakkal
bakkal

Reputation: 55448

You can render a response from a function, but what you need is return some_function() not some_function() alone, in your case some_function() does execute, but the return value is not passed on as the return value of your view myview()

So the execution flow continues and reaches return HttpResponse("This should not appear"), so that is the response you will get in your view.

If you had some_function() alone (and without return), then your view would return with no response (myview() being a function that returns nothing), and Django would complain.

You can use logic to control the flow ofcourse, provided you use return on the called functions, e.g. :

def my_view(request):

    if request['x'] == 'a':
        return function_a()
    elif request['x'] == 'b':
        return function_b()

    return some_other_response()

Just make function_x() return a valid response.

Upvotes: 2

Related Questions