Django 2.1用户保存但UserProfile不保存

时间:2018-12-24 20:34:37

标签: django signals django-2.1

我正在尝试扩展User模型,以便生成可以在url映射中使用的数据块。使用调试工具栏,我看到我的create_profile和save_profile方法注册为post_save的接收者,但是当我保存新用户时,我看到了用于创建User的SQL查询,但是没有用于创建UserProfile的相应查询。非常感谢您提供的帮助。

models.py

from django.db import models
from django.contrib.auth.models import User, PermissionsMixin
from django.utils.text import slugify
from django.urls import reverse_lazy
from django.db.models.signals import post_save

# Create your models here.
class User(User, PermissionsMixin):

    def __str__(self):
        return '@{}'.format(self.username)

class UserProfile(models.Model):
    user = models.OneToOneField(User, unique=True, related_name='profile', on_delete = models.CASCADE)
    slug = models.CharField(max_length=255, unique=True)

    def __str__(self):
        return self.slug

    def save(self, *args, **kwargs):
        slug = slugify(self.user.username)
        super().save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse_lazy(
            'accounts:profile',
            kwargs = {'slug': self.slug}
        )

    class Meta:
        db_table = 'user_profiles'

signals.py

from django.db.models.signals import post_save
from django.dispatch import receiver

from .models import User, UserProfile

@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
    if created:
        profile = UserProfile.objects.create(user=user)

@receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
    instance.profile.save()

apps.py

from django.apps import AppConfig


class AccountsConfig(AppConfig):
    name = 'accounts'

    def ready(self):
        import accounts.signals

初始化 .py

default_app_config = 'accounts.apps.AccountsConfig'

0 个答案:

没有答案