简体   繁体   中英

'RelatedManager' object has no attribute 'save' - Django

In Django, I'm using @receiver to save a model object named CampaignProfile like so:

@receiver(post_save, sender=UserModel)
def save_campaign(sender, instance, created, **kwargs):
    if created:
        instance.CampaignProfile.save()

I've created a custom user model named UserModel which needs to be linked with the CampaignProfile model, where the CampaignProfile looks something like this...

class CampaignProfile(models.Model):
    user = models.ForeignKey(UserModel, related_name='CampaignProfile', on_delete=models.CASCADE, null=True)
    campaign_title = models.CharField(max_length=50, verbose_name='Title')

However when I try to create a new super user through the Terminal then I get an error like so...

AttributeError: 'RelatedManager' object has no attribute 'save'

Does anybody know why creating a new super user would bring up this sort of error? Thanks.

That's correct - you can't call save() directly on your model - you can only call save() on object instances. Looks like you need to create some default user profile once the user is created. Try this:

@receiver(post_save, sender=UserModel)
def save_campaign(sender, instance, created, **kwargs):
    if created:
        CampaignProfile.objects.create(
           user = instance,
           title = "Profile default title"
        )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM