user1881957
user1881957

Reputation: 3378

PasswordField in Django model?

I am trying to create a simple model called Username like this:

class User(models.Model):
    username = models.CharField(max_length=100) #Id is automatically generated by Django
    password = models.CharField(max_length=100)

This is the Django model that I am trying to create. The problem is username and password attribute is stored as CharField whereas I want password to be stored as ** or encrypted form in the database.It seems like they don't have PasswordField like CharField in Django. What's the best way to do it?

Upvotes: 2

Views: 709

Answers (2)

somecallitblues
somecallitblues

Reputation: 733

Django comes with User model. It's under django.contrib.auth.models. The model has everything you need and it's would be silly to start creating your own if there is one already. You also have a user creating and authentication forms in django.contrib.auth.forms, things like set_password method in user model and heaps more stuff.

Upvotes: 0

Samuele Mattiuzzo
Samuele Mattiuzzo

Reputation: 11038

as per THE DOCS it's

password = forms.CharField( 
    widget=forms.PasswordInput(render_value=False), 
    label="Your Password"
)

and this lends to a

<input type="password" />

in your rendered form

About your storing part, you will need to store an hash of the password, not a list of * or you won't be able to retrieve it anyway. You could use the hashlib module

user.password = hashlib.sha224(user.password).hexdigest()
user.save()

of course you have to pay big attention when implementing this. This above is just a quick example, check the docs for further learning

Upvotes: 2

Related Questions