Django休息框架用户注册? [英] Django rest framework user registration?
本文介绍了Django休息框架用户注册?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在追踪本教程,但面临这些问题我无法修复:
- 注册用户后,我无法登录该用户对api因为密码没有散列
无效的密码格式或未知的哈希算法。在admin - 当我没有登录到api
我的代码:
from django.contrib.auth.models import User
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields =('password','first_name ','last_name','email')
write_only_fields =('password',)
def restore_object(self,attrs,instance = None):
#call set_password on用户对象。没有这个
#,密码将以纯文本形式存储。
user = super(UserSerializer,self).restore_object(attrs,instance)
user.set_password(attrs ['password'])#somehow not hashing
return user
解决方案
请注意,set_password()不保存对象,超级优先,您的对象已保存为原始密码。
只需使用post_save()保存密码。
pre>
def post_save(self,obj,created = False):
创建时,使用散列版本替换原始密码
如果创建:
obj.set_password(obj.password)
obj.save()
I am following this tutorial but facing these problems I can't fix:
- Upon registering user, I can not log in with that user to the api because the password is not hashed "Invalid password format or unknown hashing algorithm." in admin
- I cannot post to 'api/accounts' or see the form in the browseable api when I am not logged in to the api
My code:
from django.contrib.auth.models import User
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('password', 'first_name', 'last_name', 'email')
write_only_fields = ('password',)
def restore_object(self, attrs, instance=None):
# call set_password on user object. Without this
# the password will be stored in plain text.
user = super(UserSerializer, self).restore_object(attrs, instance)
user.set_password(attrs['password']) #somehow not hashing
return user
解决方案
Please note that set_password() does NOT save the object and since you have called the super first, your object is already saved with raw password.
Just simply use post_save() to save the password.
def post_save(self, obj, created=False):
"""
On creation, replace the raw password with a hashed version.
"""
if created:
obj.set_password(obj.password)
obj.save()
这篇关于Django休息框架用户注册?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文