gpt4 book ai didi

python - 相关对象不存在 : User has no userprofile

转载 作者:行者123 更新时间:2023-12-04 03:26:12 24 4
gpt4 key购买 nike

所以我用字段 score 扩展了我的用户。像这样:

模型.py:

class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
score = models.IntegerField(default=0);

这似乎是 recommended way .

然后我尝试访问用户的 userprofile在我看来:

View .py:
player = request.user.userprofile

这似乎也与推荐的方式一致,但这就是我得到错误的地方:
RelatedObjectDoesNotExist
User has no userprofile.

如果我改变 userprofile别的我得到另一个错误:
AttributeError
'User' object has no attribute 'flowerpot'

当我尝试以下代码时:
print request.user
print UserProfile.objects.all()

我得到控制台输出:
post_test1
[]

编辑
我有两个 super 用户,扩展用户之前创建的七个用户,扩展用户后创建的一个用户 (post_test1)。

编辑 2

很明显,我需要创建一个 post_save每当创建用户对象时创建新配置文件的处理程序。

当我阅读它时,这似乎很简单,转到 page链接到的,这是 Django 发送的所有信号的列表。我查了 post_save它说:

Like pre_save, but sent at the end of the save() method.



好的,所以我查了一下 pre_save它说:

This is sent at the beginning of a model’s save() method.



我是这样解释的:当我创建我的用户时(在我的 views.py 中) save()方法应该被调用,直到现在还没有这种情况,然后是 post_save应该发送(?),这将在创建用户对象时创建一个新的配置文件!

所以现在我准备开始看例子,所以我谷歌:
django post save example Here看起来我应该添加一些看起来像装饰器的东西 @receiver(post_save, ... Here看起来我应该更改多个文件并编写信号定义?
This one似乎也暗示了多个文件(包括 signals.py )

它看起来比我最初想象的要多得多。这里的任何人都可以解释我如何做到这一点,或者向我展示一些关于信号如何工作的好资源吗?

现在我的 create_user View 如下所示:

def create_user(request):
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():
username = form.cleaned_data["username"]
password = form.cleaned_data["password1"]
new_user = User.objects.create_user(username=username, password=password)
return redirect('play')
else:
form = UserCreationForm()

return render(request, 'antonymapp/create_user.html', {'form': form})

我应该调用 new_user.save()回来之前?如果是的话,为什么它一直工作到现在?我在测试这个 View 时创建了一堆用户。它也看起来像这里的某个地方 post_save.connect(create_profile, sender=User)应该加吗?

最佳答案

我有同样的错误,但我通过在下面创建我的信号示例解决了它
然后我编辑了我的apps.py如下:
`从 django.apps 导入 AppConfig
类博客配置(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
名称 = 'app_name'

def ready(self):
import app_name.signals`

关于python - 相关对象不存在 : User has no userprofile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36317816/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com