¡Esta es una revisión vieja del documento!
There is only one class in Django which is User, different types of users are instances of this class with other special attributes set.
Main attributes are: username, password, email, first_name, and last_name. However, there are others.
User classes and helper methods: https://docs.djangoproject.com/en/dev/ref/contrib/auth/
Using create_user function:
from django.contrib.auth.models import User user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword') # At this point, user is a User object that has already been saved to the database. user.last_name = 'Lennon' user.save()
To change user passwords we'll do:
from django.contrib.auth.models import User u = User.objects.get(username='john') u.set_password('new password') u.save()
User authenticate(), it takes credentials from keyword arguments and returns a User object if they were valid, if not returns None.
from django.contrib.auth import authenticate user = authenticate(username='john', password='secret') if user is not None: if user.is_active: print("User is valid, active and authenticated") else: print("The password is valid, but the account has been disabled!") else: print("The username and password were incorrect.")
When a request is done, it is provided a request.user attribute. If the current user has not logged in the attribute will be set to an instance of AnonymousUser, otherwise it will be an instance of User. However you can tell it using is_authenticated() method:
if request.user.is_authenticated(): # Do something for authenticated users. else: # Do something for anonymous users.
To login a user: https://docs.djangoproject.com/en/dev/topics/auth/default/#django.contrib.auth.login.
To logout use the logout function:
from django.contrib.auth import logout def logout_view(request): logout(request) # Redirect to a success page.