[英]How to save custom User model in Django during user's navigation
Hy guys, I have a custom User model in Django 2.0 containing various user data. 大家好,我在Django 2.0中有一个自定义用户模型,其中包含各种用户数据。
class User(models.Model):
username = = models.CharField(max_length=30)
_isLogged = False
# ... other custom data
Once the user is logged ( _isLogged = True
)~ in the login page, how can I save this object so I can verify in another page, say home, that the same user has already logged in? 一旦在登录页面上登录了用户(
_isLogged = True
)〜,我如何保存该对象,以便可以在另一个页面(例如home)中验证该用户是否已经登录?
NB I tried to store all the object in a session variable but it is not serializable. 注意,我尝试将所有对象存储在会话变量中,但是它不可序列化。
Many thanks. 非常感谢。
You can check if user is logged by calling the is_authenticated
function: 您可以通过调用
is_authenticated
函数来检查用户是否已登录:
if request.user.is_authenticated():
# something
This is already well described in the similar post: How to check if a user is logged in (how to properly use user.is_authenticated)? 在类似的文章中已经对此进行了很好的描述: 如何检查用户是否已登录(如何正确使用user.is_authenticated)?
You don't need any special fields (like _isLogged
) if 1) you're using default Django User, 2) you extend default User model or 3) you properly configured your own model. 如果1)您使用的是默认Django用户,2)扩展了默认的User模型,或3)您正确配置了自己的模型,则不需要任何特殊字段(例如
_isLogged
)。
For details consult the documentation . 有关详细信息,请参阅文档 。
This is very well describied in the following article . 在下面的文章中对此进行了很好的描述。 In short:
简而言之:
You declare your User model subclassing the AbstractUser
class: 您声明您的User模型子类化
AbstractUser
类:
from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass
You override the default User model by setting the following value in Django settings: 您可以通过在Django设置中设置以下值来覆盖默认的用户模型:
AUTH_USER_MODEL = 'myapp.MyUser'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.