User Model
The User model is a central part of this framework. His complete path is in.
field
The built-in User model has the following fields:
1、username: User name. 150 characters or less. Can contain numeric and English characters, as well as _, @, +, . and - characters. Cannot be empty and must be unique!
2, first_name: crooked first_name, within 30 characters. Can be empty.
3, last_name: crooked last_name, within 150 characters. Can be empty.
4. email: mailbox. Can be empty.
5, password: password. After hashing the password.
6. groups: groups. A user can belong to more than one group, and a group can have more than one user. groups is a many-to-many relationship with Groups.
7. user_permissions: permissions. A user can have multiple permissions, and a permission can be used by multiple users. And Permission belongs to a many-to-many relationship.
8. is_staff: whether or not you can access the admin site. Represents whether or not it is a staff.
9. is_active: whether it is available. For some data that want to delete the account, we set this value to 0 and it will be fine, instead of actually deleting it from the database.
10. is_superuser: whether it is a super administrator. If it is superuser, then it has all the rights of the whole website.
11. last_login: the time of the last login.
12. date_joined: the time the account was created.
Basic usage of the User model:
First we start by performing makegrations and migrate to map the model.
Create a user:
Users can be created quickly with the create_user method. This method must be passed username, email, password
from import HttpResponse from import User def index(request): user = .create_user(username='xujin',email='qq@',password='111111') return HttpResponse('success')
Then we execute the view above and go to the database, find the auth_user table and we can view the information about the user we just created
The above three parameters are mandatory parameters, the other parameters are optional. We can see in the database we set the password as if it is a messy code, in fact, this is not a messy code, but because we set the user's password after the hash encryption process, so it seems to be a messy code.
We can also change data on the user object.
def index(request): # user = .create_user(username='xujin',email='qq@',password='111111') user = (username='xujin') user.last_name = 'aaa' () # Always remember to save your data after changing it return HttpResponse('success')
But for the password field, we can't change it this way, because the password changed in this way is displayed in plaintext in the database, and won't be hashed and encrypted. We need to use a method of user to change the password.
def index(request): # user = .create_user(username='xujin',email='qq@',password='111111') user = (username='xujin') # user.last_name = 'aaa' # () # Always remember to save the data after changing it. # = '222222' # This is a mistake, it will be displayed in the database in plaintext and will not be encrypted user.set_password('222222') # Only the passwords set by this method are encrypted and stored in the database. () return HttpResponse('success')
Create a super user:
There are two ways to create a superuser.
The first way is to use code. Creating a superuser in code is very similar to creating a regular user, except that you use create_superuser. the sample code is as follows:
def index(request): user = .create_superuser(username='xujin1',email='QQ@',password='111111') return HttpResponse('success')
This way we have successfully created a super user, we can also see in the database auth_user table in the is_superuser field in the value of 1, the instant super user, and just now we created the ordinary user value is 0.
The second way to create a superuser is to use the command line:
Enter it in the terminal:
python createsuperuser
In this way, we can also create a superuser, but this is more demanding in terms of the password entered, and you can't set a very simple password.
Note: Because django's built-in user model specifies username as a unique field, we can't duplicate usernames when we create a user.
login verification
Django's authentication system already helps us with login verification. This can be achieved by simply passing. This method can only authenticate by username and password. Sample code is as follows:
from import authenticate def index(request): username = 'xujin' password = '222222' user = authenticate(request,username=username,password=password) # The user object is returned after successful authentication if user: print('Login successful: %s' % ) else: print('User name or password error!') return HttpResponse('success')
Extended User Model
Django's built-in User model is powerful enough though. But sometimes still can not meet our needs. For example, in the verification of user login , he used the username as a verification , and we sometimes need to be verified by cell phone number or email. And for example, we want to add some new fields. Then we need to extend the user model. There are several ways to extend the user model.
1. Set up the Proxy model:
If you are satisfied with the fields provided by Django, as well as the validation methods, there is nothing to change. But just need to add some operations on top of his original method. Then it is recommended to use this approach. Sample code is as follows:
Create an agent model in:
from import User class Person(User): class Meta: proxy = True # Show that this is an agent model @classmethod def get_user_number(cls): # Get the number of users return ().count()
Then after importing and using it:
from .models import Person def proxyView(request): user_number = Person.get_user_number() print(user_number) # Because we're using the proxy model, then the following two ways of writing are equivalent # () # () return HttpResponse('success')
This is the basic use of the proxy model, we can define some of our own methods without changing the methods in the original User model.
Because this is a proxy model, we can't add new fields to it. For example, if I want to add a new field to the Person model, it will report an error, which probably means that the proxy model can't add fields.
class Person(User): telephone = (max_length=11) class Meta: proxy = True # Show that this is an agent model @classmethod def get_user_number(cls): # Get the number of users return ().count()
The error message after executing makegrations is:
ERRORS: ?: (models.E017) Proxy model 'Person' contains model fields.
Although the proxy model cannot have new fields, it can have its own attribute's.
Then if we want to add new fields to the user model, then we can extend it in another way: one-to-one foreign keys
one-to-one foreign key
If you have no other requirements for the user authentication method authenticate, it is done using username and password. But if you want to add new fields on top of the original model, then you can use the one-to-one foreign key method.
First create a new model in and then connect it to User using a one-to-one foreign key:
class UserExtension(): # Define a one-to-one foreign key user = (User,on_delete=,related_name='extension') telephone = (max_length=11) school = (max_length=100) from import receiver from import post_save # This is a signal function, i.e. every time a User object is created, a new userextionsion is created for binding, using the decorator receiver @receiver(post_save,sender=User) def handler_user_extension(sender,instance,created,**kwargs): if created: # If it's the first time a user object is created, create a userextension object for binding (user=instance) else: # If you are modifying a user object, save the extension as well. ()
Then we need to map the fields we added to the database by performing makegrations and migrate.
Then write the view in:
def oneView(request): user = .create_user(username='aaaaaa',email='QQ@',password='111111') return HttpResponse('One-to-one extension of User')
Add the mapping, execute the code, and you'll see the information we've added in the database.
Since we're defining an extension model, we can't use our own authenticate to authenticate the login, so we can customize our own authenticate to authenticate the login.
def my_authenticate(telephone,password): user = (extension__telephone=telephone).first() if user: is_correct = user.check_password(password) if is_correct: return user else: print('Wrong password!') return None else: print('This user was not found') return None def oneView(request): # Create a test data user = .create_user(username='bbb',email='QQ@',password='111111') = '18888888888' () return HttpResponse('One-to-one extension of User')
In the above code we have defined a my_authenticate method to authenticate the login, and then we have created a new test data in the view oneView, at this time we have not used our own definition of the orientation, because we first of all the new test data can be used.
After running the above code, we can use our own defined method to authenticate the login.
Modify the view:
def oneView(request): # Create a test data # user = .create_user(username='bbb',email='QQ@',password='111111') # = '18888888888' # () telephone = '18888888888' password = '111111' user = my_authenticate(telephone,password) if user: print('Login successful') else: print('Login Failed') return HttpResponse('One-to-one extension of User')
The above is an extension of the User model using a one-to-one approach.
Inherits from AbstractUser
For authenticate is not satisfied, and do not want to modify the original User object on some fields, but want to add some fields, then this time you can inherit directly from, in fact, this class is also the parent class. For example, we want to add a telephone and school fields on top of the original User model, then the sample code is as follows.
First we comment out all the previous code and then write the code in:
from import AbstractUser,BaseUserManager # Customized management tools class UserManage(BaseUserManager): # _ means that it is protected and can only be called from this class. def _create_user(self,telephone,username,password,**kwargs): if not telephone: raise ValueError('Must pass on cell phone number') if not password: raise ValueError('Password must be entered') user = (telephone=telephone,username=username,**kwargs) user.set_password(password) () return user # Create regular users def create_user(self,telephone,username,password,**kwargs): kwargs['is_superuser'] = False return self._create_user(telephone=telephone,username=username,password=password,**kwargs) # Create super users def create_superuser(self,telephone,username,password,**kwargs): kwargs['is_superuser'] = True return self._create_user(telephone=telephone, username=username, password=password, **kwargs) class User(AbstractUser): telephone = (max_length=11,unique=True) school = (max_length=100) # When we use authenticate, the default fields we pass in are like username and password. # Now that we've set the value of this attribute, when authenticate is used again, it will use the field we set USERNAME_FIELD = 'telephone' objects = UserManage()
Then we need to go to settings and add a variable to tell Django that we've modified the built-in User model to use our own User model:
AUTH_USER_MODEL = ''
The name of the variable above is not random, it is required to be this name.
The value inside is the location of the User model we defined: app name. ModelName.
To use the model we defined, we first have to map it to the database, but since we changed the structure of the built-in User, and the database has been migrated with the User model that has not been changed before, we will definitely get an error if we directly migrate it now, so we need to delete all the tables, and then delete the migration file as well before we can migrate it. Then we need to delete all the tables, and then delete the migration files as well, before we can migrate. Only then can we execute the makegrations and migrate commands without reporting errors.
Then we add the view in:
from .models import User def inherit_view(request): telephone = '18888888888' password = '111111' username = 'xujin' user = .create_user(telephone=telephone,password=password,username=username) print() return HttpResponse('success')
Then execute the above code to successfully create the user and use our customized User model.
So if we now need to use authenticate to validate input information, which field should we validate?
def inherit_view(request): telephone = '18888888888' password = '111111' username = 'xujin' # user = .create_user(telephone=telephone,password=password,username=username) # print() user = authenticate(request,username=telephone,password=password) if user: print('Login successful') print() else: print('Authentication failed') return HttpResponse('success')
Why in authenticate the username parameter we pass in the telephone field. It is because in the User model, we override the USERNAME_FIELD attribute, and the value received by this attribute is the field corresponding to username in authenticate, because we change the value of USERNAME_FIELD to telephone field in User, so we need to use the telephone field, the equivalent of username does not represent the username field, but the field defined by our USERNAME_FIELD attribute.
Attention:The field corresponding to the value of the USERNAME_FIELD attribute must be set unique, i.e. the parameter unique=True needs to be set.
Above this article on Django built-in User model example details is all I share with you, I hope to give you a reference, and I hope you support me more.