How to create a password field for a user model in Django?

I am completely new to Django. In my models.py, I want a User model to represent users that sign into the application.

I see how I could have fields like fname, lname, email, and username, (simply add "first_name = models.CharField(max_length=50)", for example) but how would I have a password field so that users can be authenticated? Obviously it's a bad practice to store passwords in clear text.


There is built in django.contrib.auth user models which has following fields (username, firstname, lastname, password, email, groups, user_permissions, is_active, is_staff, is_superuser, last_login, last_joined)

you can use this built in user model by creating user object and setting password for it.

 from django.contrib.auth.models import User
 user = User.objects.create(username="username", password = "password", email="email")
 user.save()

some fields in django user models are optional except username, password and email and by default it sets some fields like is_superuser='f' if you don't specify.

it will automatically store password in hash function and In future If you want to update any user's password you can get and update

 user = User.objects.get(username="username")
 user.set_password("password")
 user.save()

You can get an current online user instance by request.user


Django's own AbstractBaseUser implementation:

@python_2_unicode_compatible
class AbstractBaseUser(models.Model):
    password = models.CharField(_('password'), max_length=128)
    last_login = models.DateTimeField(_('last login'), blank=True, null=True)

You store the password in a CharField, what you don't do is store it purely there, in fact calling the set_password for the user like below,

user.set_password("Password")

Would hash the "Password" and save it into the CharField .

Edit

If you don't base your class on AbstractBaseUser and want to implement a User class from scratch, you need to hash all passwords and then save them. Inorder to hash the passwords, you can use the make_password function.

from django.contrib.auth.hashers import make_password
hashed_password = make_password(raw_password)
链接地址: http://www.djcxy.com/p/33750.html

上一篇: 在django admin编辑用户表单中删除/隐藏用户名字段

下一篇: 如何在Django中为用户模型创建密码字段?