python - 如何使用 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'
解决方案
您需要更新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)
推荐阅读
- r - 如何避免使用 R 加载命名空间时出错
- javascript - 用户第一次打开网页时如何让serviceWorker控制页面?
- php - fopen(): SSL: 操作成功完成
- react-native - 如何等待 async/await 过程直到得到结果?
- c# - SendPrivateMessage Xamarin
- amazon-web-services - 无法通过 RDS 代理连接到 RDS PostgreSQL 数据库实例
- ajax - .Net Core Razor 页面 - 后不显眼的 ajax 后刷新字段
- javascript - 基于水平滚动位置的纯javascript隐藏和显示导航箭头
- ansible - 使用 Ansible shell 模块和gather_facts:不安全吗?
- java - Java 库的急切初始化