简体   繁体   中英

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.

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?

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:

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

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.

For details consult the documentation .

Edit: "How I should "properly" configure my own model?"

This is very well describied in the following article . In short:

  1. You declare your User model subclassing the AbstractUser class:

     from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass 
  2. You override the default User model by setting the following value in Django settings:

     AUTH_USER_MODEL = 'myapp.MyUser' 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM