I created a user form / user view in Django to add additional user attributes through another model. I used set_password to set the password for the newly created user to the password entered on the form, but I found that the saved passwords are not hashed.
the form:
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = User
fields = ('username', 'email', 'password')
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = ('theclass',)
widgets = {
'theclass': forms.CheckboxSelectMultiple(),
}
class TeacherForm(forms.ModelForm):
class Meta:
model = Teacher
fields = ('theclass',)
widgets = {
'theclass': forms.CheckboxSelectMultiple(),
}
View:
def register_student(request):
context = RequestContext(request)
registered = False
if request.method == 'POST':
user_form = UserForm(data=request.POST)
student_form = StudentForm(data = request.POST)
if user_form.is_valid() and student_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save
student = student_form.save(commit = False)
student.user = user
student.save()
registered = True
else:
user_form = UserForm()
student_form = StudentForm()
return render_to_response('classapp/register_student.html', {'user_form': user_form, 'student_form': student_form, 'registered': registered}, context)
def register_teacher(request):
context = RequestContext(request)
registered = False
if request.method == 'POST':
user_form = UserForm(data=request.POST)
teacher_form = TeacherForm(data = request.POST)
if user_form.is_valid() and teacher_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save
teacher = teacher_form.save(commit = False)
teacher.user = user
teacher.save()
registered = True
else:
user_form = UserForm()
teacher_form = TeacherForm()
return render_to_response('classapp/register_teacher.html', {'user_form': user_form, 'teacher_form': teacher_form, 'registered': registered}, context)
When I register a user through this form, the login is invalid. I checked the user information in Admin and found that the password field indicated: Incorrect password format or unknown hash algorithm. I also synchronized db and opened a shell and manually extracted user objects created using my registration form and found that the user password is not hashed, for example:
>>> from django.contrib.auth.models import User
>>> user = User.objects.get(username = "username")
>>> user.password
u'password'
>>> user = User.objects.get(username = "superuser")
>>> user.password
u****hashed password****
, Admin, , . , set_password (raw_password) .