Django:set_password不是哈希密码?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django:set_password不是哈希密码?相关的知识,希望对你有一定的参考价值。
我在Django中创建了一个自定义用户注册表单/视图,以便我可以通过不同的模型包含其他用户属性。我已经使用set_password将新创建的用户的密码设置为在表单中输入的密码,但我发现保存的密码没有经过哈希处理。
形成:
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(),
}
视图:
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)
当我通过此表单注册用户时,登录无效。我检查了Admin上的用户信息,发现密码字段说:密码格式无效或者哈希算法未知。我还同步了db并打开了shell并手动检索了使用我的注册表创建的用户对象,发现用户密码没有被哈希,如下所示:
>>> 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)自动处理哈希。
答案
在你的观点中,我认为应该如此
user.save()
在线下面
user.set_password(user.password)
你没有写括号(括号)。这就是为什么在哈希密码后没有调用save
方法的原因。
另一答案
user.set_password(user.password)
user.save()
以上是关于Django:set_password不是哈希密码?的主要内容,如果未能解决你的问题,请参考以下文章