我创建了一个新的UserProfile模型。下面的代码:
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
import logging
logger = logging.getLogger(__name__)
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, default=1)
bio = models.TextField(max_length=500, blank=True)
location = models.CharField(max_length=30, blank=True)
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.userprofile.save()
此代码正在被信号触发并正常工作,但是它保存了UserProfile对象,而不是单个字段(附加图像)。我在做什么错了?
我需要编写自定义管理器吗?还是我需要以某种方式覆盖save()方法?
预先感谢
答案 0 :(得分:0)
我通过创建扩展AbstractUser的自定义用户模型来解决此问题。