如何使用django-tastypie API以编程方式创建或注册用户? [英] How to create or register User using django-tastypie API programmatically?
本文介绍了如何使用django-tastypie API以编程方式创建或注册用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的代码下面有一个工作,它创建用户对象并保存,但它不保存密码:
My code below kinda works, it creates the User object and saves but it doesn't save the password:
class CreateUserResource(ModelResource):
class Meta:
allowed_methods = ['post']
object_class = User
authentication = Authentication()
authorization = Authorization()
include_resource_uri = False
fields = ['username']
def obj_create(self, bundle, request=None, **kwargs):
try:
bundle = super(CreateUserResource, self).obj_create(bundle, request, **kwargs)
except IntegrityError:
raise BadRequest('That username already exists')
return bundle
如果我向Meta字段添加密码,那么它会保存原始密码,但不保存它。我做错了什么?
If I add 'password' to the Meta fields then it does save the raw password but not hashing it. What am I doing wrong?
所以这对我有用:
def obj_create(self, bundle, request=None, **kwargs):
username, password = bundle.data['username'], bundle.data['password']
try:
bundle.obj = User.objects.create_user(username, '', password)
except IntegrityError:
raise BadRequest('That username already exists')
return bundle
推荐答案
您需要使用方法set_password user.set_password(bundle.data.get('password'))
或使用User对象的create_user方法。
When creating a user you need either use method set_password user.set_password(bundle.data.get('password'))
or use a create_user method of User object.
user = User.objects.create_user(bundle.data.get('username'), bundle.data.get('email'), bundle.data.get('password'))
所以这样的事情会适合你: p>
So something like this would work for you:
def obj_create(self, bundle, request=None, **kwargs):
try:
bundle = super(CreateUserResource, self).obj_create(bundle, request, **kwargs)
bundle.obj.set_password(bundle.data.get('password'))
bundle.obj.save()
except IntegrityError:
raise BadRequest('That username already exists')
return bundle
这篇关于如何使用django-tastypie API以编程方式创建或注册用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文