如何在Django中为用户模型创建密码字段? [英] How to create a password field for a user model in Django?

查看:289
本文介绍了如何在Django中为用户模型创建密码字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Django完全陌生。在我的models.py中,我想要一个用户模型来代表登录到应用程序中的用户。

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

我知道如何拥有fname,lname,email和username等字段(例如,只需添加 first_name = models.CharField(max_length = 50)) ),但我将如何设置一个密码字段,以便对用户进行身份验证?显然,以明文形式存储密码是一种不好的做法。

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.

推荐答案

内置django.contrib.auth用户模型具有以下字段(用户名,名字,姓氏,密码,电子邮件,组,user_permissions,is_active,is_staff,is_superuser,last_login,last_joined)

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()

django用户模型中的某些字段是可选的,但用户名,密码和电子邮件除外,默认情况下,如果未指定,则会设置某些字段,例如is_superuser ='f'。

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()

您可以通过request.user

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

这篇关于如何在Django中为用户模型创建密码字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆