django将Charfield保存为字符串吗?

时间:2018-01-15 18:26:08

标签: django

对这个问题如此基本和困惑。

我试图在django中看到一些对象的类型并且等于一起。 见下面的例子:

print(type(request.data['token']))
>>> <class 'str'>

和:

obj = UserProfile.objects.get(pk=1)
print(type(obj.first_token))
>>><class 'app.models.first_token.token'>

obj.first_token是一个charfield。 那我怎么知道first_token存储为字符串?

if request.data['token'] == obj.first_token:

这两个对象是否相等,如果它们具有相同的值? models.py

class FirstToken(models.Model):
    token = models.CharField(max_length=6, blank=True)

def __str__(self):
    return self.token

    def save(self, *args, **kwargs):
        chars = string.ascii_lowercase + string.digits
        size = 6
        self.token ="".join(random.choice(chars)for _ in range(size))
        super(FirstToken, self).save(*args, **kwargs)


class UserProfile(models.Model):
    """User Profile model """
    user = models.OneToOneField(
                            User,
                            on_delete=models.CASCADE,
                            related_name='user_profile')
    first_token = models.OneToOneField(
                               FirstToken,
                  on_delete=models.CASCADE, 
                  related_name='first_token',blank=True)

def post(self, request,phonenumber):
        obj = UserProfile.objects.get(phonenumber=request.data['phonenumber'])

        if request.data['token'] == obj.first_token.token:
            obj.is_active = True
            obj.save()
            return Response({"message": "User has been activate"})
        elif request.data['token'] != obj.first_token:
            return Response({"message" : "Token not provided"},
                                status=status.HTTP_400_BAD_REQUEST)
        return Response(obj)

1 个答案:

答案 0 :(得分:2)

正如daniel roseman所说.obj没有is_active property.for saving.cause userprofile与用户django模型有OneToOne关系。你应该这样做:

obj.user.is_active = True
obj.user.save()