首页 > 解决方案 > 如何使用 Django 将配置文件链接到新创建的用户

问题描述

刚刚使用 Django 完成了一个网站,在创建用户或超级用户后我被卡住了。

由于某种原因,我以前使用的相同代码不再起作用,现在每当我创建一个新用户时,它都会被保存(因为我无法创建另一个具有相同名称的用户)但不是它的配置文件。

所以现在,在注册表格之后,用户应该被重定向到配置文件页面,这会带来一个错误。如果我尝试重新启动服务器并再次登录,则会出现相同的错误。

这是我的信号.py

from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import Profile

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

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

和models.py

from django.db import models
from django.contrib.auth.models import User
from PIL import Image


class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')

    def __str__(self):
        return f'{self.user.username} Profile'

    def save(self):
        super().save()

        img = Image.open(self.image.path)

        if img.height > 300 or img.width > 300:
            output_size = (300, 300)
            img.thumbnail(output_size)
            img.save(self.image.path)


TypeError at /register/
save() got an unexpected keyword argument 'force_insert'

标签: pythondjangodjango-signalsdjango-users

解决方案


您需要更新save方法以匹配其original function signature. 基本上,您需要通过超级函数传递参数和关键字参数才能使其工作:

class Profile(models.Model):
    # rest of the code

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        img = Image.open(self.image.path)
        if img.height > 300 or img.width > 300:
            output_size = (300, 300)
            img.thumbnail(output_size)
            img.save(self.image.path)

推荐阅读