1
votes

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

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.

2
Don't do this there are half a dozen tried and tested user authentication apps in django. django-allauth in particular stands out. Please use one of them.e4c5

2 Answers

4
votes

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

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

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

1
votes

Django's own AbstractBaseUser implementation:

@python_2_unicode_compatible
class AbstractBaseUser(models.Model):
    password = models.CharField(_('password'), max_length=128)
    last_login = models.DateTimeField(_('last login'), blank=True, null=True)

You store the password in a CharField, what you don't do is store it purely there, in fact calling the set_password for the user like below,

user.set_password("Password")

Would hash the "Password" and save it into the CharField.

Edit

If you don't base your class on AbstractBaseUser and want to implement a User class from scratch, you need to hash all passwords and then save them. Inorder to hash the passwords, you can use the make_password function.

from django.contrib.auth.hashers import make_password
hashed_password = make_password(raw_password)