0

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?

N.B. I tried to store all the object in a session variable but it is not serializable.

Many thanks.

decadenza
  • 2,380
  • 3
  • 18
  • 31

1 Answers1

1

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'
    
Siegmeyer
  • 4,312
  • 6
  • 26
  • 43
  • I'd go for the option 3) but can you explain how I should "properly" configure my own model??? – decadenza Mar 09 '18 at 06:55
  • Thank you, but the Django-way to do this is rather obscure... For example in the documentation I cannot find how to define my `is_authenticated()` method. I still prefer to do my custom model and check data using session, separated from Django user model. – decadenza Mar 09 '18 at 17:09
  • What do you mean by define? is_authenticated is a default method, you can use it out-of-the-box or override it using Python. – Siegmeyer Mar 09 '18 at 17:11
  • How does a user become "authenticated"? I have a special test to do before checking username and password. – decadenza Mar 10 '18 at 13:55