如何在django中为每个用户设置唯一的对象?

时间:2019-05-15 08:58:21

标签: python django sqlite django-models

我有一个关于Django模型的问题,我该如何为每个用户将字段设置为django中表的True = True。我在下面有表令牌,当我添加新令牌时,它不会通过内置的django信号自动创建令牌配置文件,我想为每个用户使用ProfileToken的唯一uid。告诉我如何。谢谢

from django.db import models
from accounts.models import CustomeUser
from django.db.models.signals import post_save
import facebook
# Create your models here.
class Token(models.Model):
    access_token = models.CharField(max_length=255)
    user = models.ForeignKey(CustomeUser, related_name='tokens', on_delete=models.CASCADE)
    def __str__(self):
        return self.access_token



class TokenProfile(models.Model):
    token = models.OneToOneField(Token, on_delete=models.CASCADE)
    name = models.CharField(max_length=50)
    uid = models.CharField(max_length=50, unique=False)
    profile_picture_link = models.CharField(max_length=255)
    profile_link = models.CharField(max_length=255)
    def __str__(self):
        return '{0} - {1}'.format(self.name, self.uid)


def create_profile_token(sender, instance, created, **kwargs):
    if created:
        access_token = instance.access_token
        graph = facebook.GraphAPI(access_token=access_token)
        info = graph.get_object('me')
        name = info['name']
        uid = info['id']
        profile_picture_link = 'https://graph.facebook.com/v3.1/{0}/picture?type=small&redirect=true'.format(uid)
        profile_link = 'https://www.facebook.com/{0}'.format(uid)
        profile_token = TokenProfile.objects.create(token=instance, name=name, uid=uid, profile_picture_link=profile_picture_link, profile_link=profile_link)


post_save.connect(create_profile_token, sender=Token)

0 个答案:

没有答案