django User model

时间:2023-03-08 20:27:20

django User model operation

this tutorial will guide us to know how to manipulate django User model.

Read User object derived from database

from django.contrib.auth.models import User

# Those two lines are different even if there is only one user 'admin' who registered before

auser = User.objects.get(username = 'admin')   # unique only one var
buser = User.objects.filter(username = 'admin') # var type the same as " allusers " allusers = User.objects.all()

Now let's check out how it shows.

in python shell,

>>>allusers

[<User: admin>]

>>>auser

<User: admin>

>>>buser

[<user: admin>]

>>>allusers == buser

Flase

Now let's see how to write data for User

Creating users

The most direct way to create users is to use the included create_user() helper 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. You can continue to change its attributes
# if you want to change other fields.
>>> user.last_name = 'Lennon'
>>> user.save()

If you have the Django admin installed, you can also create users interactively.

 For more information about user authentication, user permissions, user groups, Please visit

authenticate (验证身份)

the operation downside will directly talk to database model

from django.contrib import auth
user = auth.authenticate(username='john', password='secret')
if user is not None:
print "Correct!"
else:
print "Invalid password."