python - Django 保存后无法登录

标签 python django django-rest-framework

我的 django-rest-server 上有 TokenAuthentification。 注册后login工作正常,但是当我使用旧字段调用更新时,我无法再登录(无法使用提供的凭据登录)作为响应。我做错了什么?

更新代码:

class ClientSerializer(serializers.ModelSerializer):
    username = serializers.CharField(source='user.username')
    first_name = serializers.CharField(source='user.first_name')
    last_name = serializers.CharField(source='user.last_name')
    email = serializers.CharField(source='user.email')
    password = serializers.CharField(source='user.password')
    profile_photo = serializers.ImageField(source='details_sample.profile_photo', required=False)

    class Meta:
        model = Client
        fields = ('id', 'username', 'first_name', 'last_name', 'email', 'password', 'profile_photo', 'phone')

    def update(self, instance, validated_data):

        if validated_data.get('user') is not None:
            instance.user.set_password(validated_data['user'].get('password', instance.user.password))
            instance.username = validated_data['user'].get('username', instance.user.password)
            instance.first_name = validated_data['user'].get('first_name', instance.user.password)
            instance.last_name = validated_data['user'].get('last_name', instance.user.password)
            instance.user.save()

        instance.phone = validated_data.get('phone', instance.phone)

        instance.save()
        return instance

登录网址:

url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),

token 创建:

@receiver(post_init, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    if created:
        Token.objects.create(user=instance)

最佳答案

我认为你的麻烦在这里:

instance.user.set_password(validated_data['user'].get('password', instance.user.password))
#                                                                 ^^^^^

尝试替换:

password = validated_data['user'].get('password', None)
if password:
      instance.user.set_password(password)

关于python - Django 保存后无法登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46039061/

相关文章:

python - 将字符串的值视为 .. 属性名称?

Django:如何在 "apps"文件夹中启动应用程序

django - 按用户过滤反向关系,并在 Django Rest Framework 中仅返回一个对象

python - 无法在 Django Rest 框架中创建没有字段的模型

django - 如何导入csv

python - Django-REST : Get User by username instead of primary-key

python - 不能根据数据在现有图上绘制计算的质心值

python - 带有 Python : 3. 10.0b4 的 PyInstaller - 导入错误:没有名为 _bootlocale 的模块

python - 子图中的 wspace 和 hspace,轴的宽度 - python3

ListView 中的 Django object_list 有两个模型