我有三种型号。当我创建一个User
时,它将创建一个UserProfile
。创建UserProfile
时,应创建一个Artist
。一切正常,但是当我更新UserProfile
时出现错误。
models.py
:
class Artist(models.Model):
CHOICES = (
(0, 'celebrities'),
(1, 'singer'),
(2, 'comedian'),
(3, 'dancer'),
(4, 'model'),
(5, 'Photographer')
)
name = models.CharField(max_length=100,null= True)
artist_category = models.IntegerField(choices = CHOICES, null=True)
artist_image = models.ImageField(upload_to= 'media',null=True)
bio = models.TextField(max_length = 500)
def __str__(self):
return str(self.name)
class UserProfile(models.Model):
CHOICES = (
(0, 'celebrities'),
(1, 'singer'),
(2, 'comedian'),
(3, 'dancer'),
(4, 'model'),
(5, 'Photographer')
)
user = models.OneToOneField(CustomUser, related_name='userprofile', on_delete= models.CASCADE)
artist = models.ForeignKey(Artist,related_name='userprofile', on_delete=models.CASCADE, null=True)
name = models.CharField(max_length=100, null=True)
artist_category = models.IntegerField(choices= CHOICES, null=True)
mobile_number = PhoneNumberField(null=True)
country = CountryField(default = 'IN')
city = models.CharField(blank=True, max_length=100)
bio = models.TextField(blank=True)
def __str__(self):
return str(self.user)
def create_profile(sender,instance, created,**kwargs):
if created:
data = {
'name': instance.name
}
UserProfile.objects.create(user=instance,**data)
post_save.connect(create_profile,sender=CustomUser)
@receiver(post_save, sender= CustomUser)
def save_profile(sender,instance,**kwargs):
instance.userprofile.save()
def create_artist(sender,instance,created,**kwargs):
if created:
data = {
'name': instance.name,
'artist_category': instance.artist_category,
'bio': instance.bio
}
Artist.objects.create(**data)
post_save.connect(create_artist,sender=UserProfile)
@receiver(post_save, sender= UserProfile)
def save_artist(sender,instance,**kwargs):
instance.artist.save()
它给了我这个错误:
`File "/home/tboss/Desktop/environment/celeb/celeb/main_site/models.py", line 155, in create_artist
instance.artist.save()
AttributeError: 'NoneType' object has no attribute 'save'
`.............................................. ............
答案 0 :(得分:0)
问题在于,在post_save
的 first UserProfile
信号中,您正在创建一个新的Artist
实例,但是未连接与您的UserProfile
实例。
删除create_artist
和save_artist
信号并添加以下内容:
@receiver(post_save, sender= UserProfile)
def update_artist(sender,instance,created,**kwargs):
if created:
data = {
'name': instance.name,
'artist_category': instance.artist_category,
'bio': instance.bio
}
instance.artist = Artist.objects.create(**data)
instance.save()
else:
instance.artist.save()
对于同一模型,您有两个 post_save
信号,可以合并为一个。