[Answered ]-How does Django ModelBackend.authenticate work?

2👍

authenticate() doesn’t ‘work’ by itself.

If your project or application implements a login form then you, or the developer of the app you use for authentication, will call authenticate().

For example, if you have a login form with a username & password field then you’d call authenticate(username, password) in your post() method.

For example;

if request.method == 'POST':
    # Gather the username and password provided by the user.
    # This information is obtained from the login form.
    username = request.POST['username']
    password = request.POST['password']

    # Use Django's machinery to attempt to see if the username/password
    # combination is valid - a User object is returned if it is.
    user = authenticate(username=username, password=password)
    # If we have a User object, the details are correct.
    # If None (Python's way of representing the absence of a value), no user
    # with matching credentials was found.
    if user:
        # Is the account active? It could have been disabled.
        if user.is_active:
            # If the account is valid and active, we can log the user in.
            # We'll send the user back to the homepage.
            login(request, user)
            return HttpResponseRedirect('/rango/')
        else:
            # An inactive account was used - no logging in!
            return HttpResponse("Your Rango account is disabled.")
    else:
        # Bad login details were provided. So we can't log the user in.
        print "Invalid login details: {0}, {1}".format(username, password)
        return HttpResponse("Invalid login details supplied.")

See here for the full write up on this code, or check out the official django docs on authenticate().

Leave a comment