簡體   English   中英

如何使用 Django 將配置文件鏈接到新創建的用戶

[英]How to link a profile to a newly created user using 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 基本上,您需要通過超級 function 傳遞 arguments 和關鍵字 arguments 才能使其工作:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM