0

I'm calling this view (in Django) with an ajax request containing a username to query the database for. It returns a server error that the user object (in the except condition) is being used before it is defined, but it is defined in the line above!

So I thought maybe it was a scope problem, and put user = None at the start of the elif, knowing it would be changed in the try, but then I get None has no value DoesNotExist.

def signup(request):
    if request.method == 'GET':
        return render_to_response('signup.html', context_instance=RequestContext(request))
    elif request.is_ajax(): 
    #query db for user with username provided via ajax, return if it exists
        try:    
            user = User.objects.get(username=request.POST["username"]) 
        except User.DoesNotExist:
            return HttpResponse("false",context_instance=RequestContext(request))
        else:
            return HttpResponse("true", context_instance=RequestContext(request))

function usernameCheck(){
    $.ajax({
        type:'POST',
        url:"http://omnicloud.me/signup", 
      data:{username: $("#username").value}, 
      success:function(response){
        if(response=="true"){
           $('#passAlert').innerHTML("Sorry, that username is already taken")
        }
        },
        headers:{"X-CSRFToken", getCookie('csrftoken')}
    });

    return !($('#passAlert').value == "Sorry, that username is already taken")
}
Chris
  • 11,819
  • 19
  • 91
  • 145

1 Answers1

2

except user.DoesNotExist: should reference the user model (User) not the user object (user) as in except User.DoesNotExist:

Mark Lavin
  • 24,664
  • 5
  • 76
  • 70
  • 3
    Wondering why he copied the code I gave him, yet changed `User` to `user` on that line? http://stackoverflow.com/questions/8223784/sending-ajax-request-to-server-with-jquery/#8229874 – Chris Pratt Nov 22 '11 at 18:20
  • Oh wow I didn't realize this was part of a previous question. – Mark Lavin Nov 22 '11 at 18:23
  • @ChrisPratt @ChrisPratt I had it like that originally and it is giving me a 500 error: `
    "Key 'username' not found in <QueryDict: {}>"
    ` so I thought it meant the username wasn't found (expected) and it wasn't handling the error correctly, since it included "Query". so perhaps my POST isn't including the username (code added)
    – Chris Nov 22 '11 at 18:58
  • 1
    always use request.POST.get("key", "default value") – benjaoming Nov 22 '11 at 19:55
  • @benjaoming so this protects against the POST key not being there, but is there any reason (assuming that they actually put in a username) that my code wouldn't put it there? – Chris Nov 22 '11 at 20:36
  • well, would you want your whole program to fail with an exception or gracefully? Besides, it's input from a network... basically that's what has to be treated with the deepest of all distrust. Just a rule of thumb. So instead of making a decision of whether or not, just do it :) – benjaoming Nov 23 '11 at 17:37