按关系更新用户名导致密码消失。

2024-09-30 20:22:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我对ModelResource的元类中的excludes属性有问题。在

我为用户创建了ModelResource。在

class UserResource(ModelResource):
    class Meta:
        serializer = Serializer(formats=['json'])
        queryset = User.objects.all()
        excludes = ['password', 'is_active', 'is_staff', 'is_superuser']
        resource_name = 'user'
        always_return_data = True
        authentication = ApiKeyAuthentication()
        authorization = UserAuthorization()

它非常类似于doc.中的那个

我发送PUT来更新username,使用:
{"username": "bara", "first_name": "bara", "last_name": "", "email": "bara@example.com", "last_login": "2013-10-09T15:32:55.056235","id": 7, "date_joined": "2013-10-09T15:32:55.056235"}

一切都很完美。在

但我不想直接使用这个资源,我想使用这个资源。在

^{pr2}$

我发送PUT以更新username,内容如下: { "user": {"username": "barabara", "first_name": "bara", "last_name": "", "email": "bara@example.com", "last_login": "2013-10-09T15:32:55.056235", "id": 7, "date_joined": "2013-10-09T15:32:55.056235"}, "gender": 0, "birth_date": null}

而且它似乎工作得很好,但它不起作用。密码在第二种情况下被重写了。 我得到ValueError: Unknown password hashing algorithm.
在管理面板中,我看到: enter image description here

我试图在ProfileResource的Meta-like user__password和{}中设置{},但似乎没有帮助。在

附加信息:
-用户和配置文件是一对一。
-Python2.7、Django 1.4.3、Tastype0.9.12

编辑:
很抱歉让您感到困惑,但这只发生在username更新过程中。从所有用户领域休息良好。在


Tags: 用户namedateputisusernamepasswordmeta
2条回答

我不得不实施肮脏的黑客仍然没有很好的测试,所以请小心:
ProfileResource方法:

def obj_update(self, bundle, **kwargs):
        """
        Additional operations for changing username.

        Changes username in database.
        """
        bundle = super(ProfileResource, self).obj_update(bundle, **kwargs)

        username, api_key = self.get_credentials(bundle.request)
        profile = Profile.get_logged(username, api_key)
        if profile:
            try:
                if bundle.data['username'] and bundle.data['username'] != profile.user.username:
                    try:
                        User.objects.get(username=bundle.data['username'])
                        logging.warning('Username %s Already exists cannot update.' % bundle.data['username'])
                    except User.DoesNotExist:
                        profile.user.username = bundle.data['username']
                        profile.user.save()

            except KeyError:
                pass

        return bundle

我知道这不是解决办法。另一个选择是直接使用UserResource。在

我不确定,但我认为问题在于,当您执行put操作时,会创建新用户,因为它会更新用户字段(例如,将现有用户替换为新用户,新用户没有密码字段,它不会合并两个用户)。在

也许试着用别的动词?在

相关问题 更多 >