简体   繁体   中英

create django user who can not login

I want to create a user whom I'm using as a ForeignKey and i don't want those users can login to system. I have no idea how to go on. (about setting set_unusable_password() or None, and how to perform it):

my accounts.py file is as

class User(AbstractBaseUser):
    GENDER = (("MALE", "Male"), ("FEMALE", "Female"))
    
    user_type = models.CharField(max_length=50, choices=Types.choices, default=Types.PATIENT)
    full_name = models.CharField(max_length=255, blank=True, null=True)
    phone = models.CharField(max_length=255, unique=True)
    email = models.CharField(max_length=255, blank=True, null=True, unique=True)
    active = models.BooleanField(default=False)
    gender = models.CharField(max_length=15, choices=GENDER)
    admin = models.BooleanField(default=False)
    staff = models.BooleanField(default=False)
    timestamp = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    USERNAME_FIELD = "phone"  # username
    REQUIRED_FIELDS = []
    objects = UserManager()

thanks in advance guys. <3

you can use the is_active field of the user record

is_active Boolean . Designates whether this user account should be considered active. We recommend that you set this flag to False instead of deleting accounts; that way, if your applications have any foreign keys to users, the foreign keys won't break.

In View you should also check whether the user is active or not. For Eg:

def user_login(request):
    if request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        user = authenticate(username = username,password = password)
        if user is not None and user.active:
            login(request,user)

As you have overide your user model and changed active field from is_active.If active field is False then it will not allow the user to log in if the user is active it will allow user to log in.

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