djangodjango-auth-models

Django authentication/user create functions


I'm trying to start a project in Django, where users can register on my site and subsequently login/logout when they visit it.

I have found a template for a user creation view, that looks like this:

from django.views.generic import CreateView
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import authenticate, login

class CreateUserView(CreateView):
    template_name = 'register.html'
    form_class = UserCreationForm
    success_url = '/'

    def form_valid(self, form):
        valid = super(CreateUserView, self).form_valid(form)
        username, password = (
            form.cleaned_data.get('username'),
            form.cleaned_data.get('password1')
        )
        new_user = authenticate(username=username, password=password)
        login(self.request, new_user)
        return valid

Now, I'm wondering why a call to authenticate with a non-existing username should create a new user. I'm trying to find any documentation for the imported functions authenticate and login, however, I can only find documentation for the User-model, AnonymousUser object, Permission-model, Group-model, some authentication backends and signals/validators, but I don't find any documentation for (standalone) functions authenticate and login. Can someone provide me the with a link to the relevant documentation or at least confirm that the way as they are used above is (still?) correct?


Solution

  • I think there's a bit of misunderstanding here maybe the choice of variable name is to blame. The authenticate function does not create a new user but returns the user object. docs

    It is the UserCreationForm that creates the user. docs