python
Create a password field in Django model
The methods explained in this post can be used to create a password field in the forms created using the Django model.
# models.py
from django import models
class Student(models.Model):
username = models.CharField(max_length=60)
password = models.CharField(max_length=30)
# forms.py
from django import forms
class StudentForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = Student
In the above code snippet:
- Created a Django model named Student in models.py file and created two fields in it - username and password.
- We want to show the password field in password format on the form created using Django forms.
- In the forms.py file, we have created a form named StudentForm and for the password field, we have used widget=forms.PasswordInput to show it as a password input on the form.
Note that we are using widget=forms.PasswordInput in forms.py not on models.py or views.py
You can also use the below code to make a model field password.
from django import forms
class StudentForm(forms.ModelForm):
class Meta:
model = Student
widgets = {
'password': forms.PasswordInput(),
}
# models.py
from django import models
class Employee(models.Model):
name = models.CharField(max_length=30)
password = models.CharField(max_length=20)
# forms.py
from django import forms
class EmployeeForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = Employee
Here, we have created a model named Employee and we are creating its field password to password format.
Was this helpful?
Similar Posts