views:

119

answers:

2

Hello,

I have a django view that looks like...

    def add_user(request):
        if User.objects.get(username__exact = request.POST['username']):
            context = { 'message': "Username already taken"}
            return render_to_response("mytemplate.html", context, RequestContext(request))

        newUser = User(username="freeandclearusername")
        newUser.save()

        #then other code that is related to setting up a new user.

The other code that is related to setting up the user is still ran even if the initial conditional statement fails and the "return render_to_response()" is called.

The page is rendered with the correct context but other information is added to the database after the initial return. I thought that the code after the "return render_to_response()" would not run.

Can anyone confirm or explain this?

UPDATE....

Ok so if I add a conditional....

def add_user(request):
    if User.objects.get(username__exact = request.POST['username']):
        bad_user = True
        context = { 'message': "Username already taken"}
        return render_to_response("mytemplate.html", context, RequestContext(request))

    newUser = User(username="freeandclearusername")
    newUser.save()

    if bad_user != True:
        #then other code that is related to setting up a new user.
        context = { 'message': "Username is great!!!!!"}
        return render_to_response("mytemplate.html", context, RequestContext(request))

This behaves as expected. Also if I remove the RequestConext() it seems to behave correctly as well.

Any ideas? I think the problem lies in how I'm using RequestContext.

+1  A: 

The return statement will indeed terminate the function. So if you see other code being executed, you either

  • don't execute the return statement, and thus produce the output somehow differently, or
  • have other code (before the function is called, or in a middleware) that makes the database changes.
Martin v. Löwis
A: 

You are correct, assuming your conditions are met, the view will exit on your return statement. The only other thing I can think of that hasn't already been mentioned is indentation -- double-check that you do not have a mix of tabs and spaces. That can sometimes result in the unexpected.

Ryan Duffield