首页 \ 问答 \ 用户没有用户配置文件(User has no userprofile)

用户没有用户配置文件(User has no userprofile)

所以我用这样的现场score扩展了我的用户:

models.py:

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

这似乎是沿着推荐方式的路线

然后我尝试在我的视图中访问用户userprofile:

views.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
[]

编辑
我有两个超级用户,
在扩展用户之前创建的七个用户
和一个用户(post_test1),我是在扩展用户之后创建的。


EDIT_2

你好,我们又见面了!

所以它清楚地表明我需要的是

创建一个post_save处理程序,以便在创建User对象时创建新的配置文件

这看起来很简单,当我读它时,去到链接到的页面是Django发送的所有信号的列表。 我抬头看了一下post_save,它说:

像pre_save一样,但在save()方法结束时发送。

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

这是在模型的save()方法开始时发送的。

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

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

它看起来还有很多,我首先想到了。 这里的任何一个人是否可以解释我是如何做到这一点,或者向我展示信号如何工作的一些好资源?

现在我的create_users视图如下所示:

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()吗? 如果是的话,为什么直到现在呢? 在测试此视图时,我创建了一堆用户。 它也看起来像在这里post_save.connect(create_profile, sender=User)应该被添加? 我显然很迷茫


So I've extended my user with the field score like this:

models.py:

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

which seemed to be along the lines of the recommended way

Then I tried to access the users userprofile in my views:

views.py:

player = request.user.userprofile

which seemed to align with the recommended way as well. But that is where I get my error:

RelatedObjectDoesNotExist
User has no userprofile.

If I change userprofile to something else I get another error:

AttributeError
'User' object has no attribute 'flowerpot'

When I try the following code:

print request.user
print UserProfile.objects.all()

I get the console output:

post_test1
[]

EDIT
I have two superusers,
seven users I created before extending the user
and one user (post_test1) I created after extending the user.


EDIT_2

Hi again!

So it seams clear that what I need is to

create a post_save handler that creates a new profile when ever the User object is created

This seemed simple enough when I read it, went to the page that was linked to which was a list of all the signals Django sends. I looked up post_save and it said:

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

Alright, so I look up pre_save and it says:

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

I've interpreted it like this: When I create my user (in my views.py) a save() method should be called (which hasn't been the case up till now) and after that a post_save should be sent(?) which will create a new profile when ever the User object is created!

So now I'm ready to start looking at examples, so I google:
django post save example
Here it looks like I'm supposed to add something that looks like a decorator @receiver(post_save, ...
Here it looks like I'm supposed to alter multiple files and write a signal definition?
This one also seem to imply multiple files (including a signals.py)

It looks like there's a lot more too it then I first thought. Could any one here either explain how I'm to do this or show me to some good resources on how signals work ?

Right now my create_users view look like this:

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})

Should I call new_user.save() before returning? If yes, why has it worked up till now? I have a bunch of users that I've created while testing this view. It also looks like somewhere around here post_save.connect(create_profile, sender=User) should be added? I'm obviously quite lost here...


原文:https://stackoverflow.com/questions/36317816
更新时间:2022-09-23 12:09

最满意答案

我想这只是因为方法TryDequeue()有一个int类型的参数,即使你不使用它也必须给它一个。


I guess it's just because the method TryDequeue() has an parameter of type int, and you have to give it one even if you don't use it.

相关问答

更多
  • 在VS中启用Auto-Formatting event以paste from clipboard (工具 - >选项) - 只要您将代码粘贴到XAML文件中,它就会格式化您的xaml,但您需要手动修复一些间距问题。 Enable Auto-Formatting event in your VS for paste from clipboard(Tools -> Options) - It will format your xaml as soon you paste code in your XAML fi ...
  • 我终于弄清楚如何解决我的问题,尽管我正在触发我的下载事件异步它似乎仍然在主线程上执行,这意味着在任何下载之前调用this.CountDown.Wait()完成然后我的this.CountDown没有被发信号因此this.CountDown永远不会被设置为零,这仍然等待。 我在这做了什么: 在foreach我用ThreadPool.QueueUserWorkItem替换了对方法LoadSources(uri)的调用,该方法将一个方法排队执行。 该方法在线程池线程可用时执行。 ThreadPool.QueueU ...
  • 我们必须猜测您的大部分输入文档和代码。 我怀疑该body是该HTML文档的最外层元素。 用于搜索此script元素的有意义的Xpath表达式将是 //script[contains(., 'fid')] 如果文本内容包含fid则会在文档中的任何位置找到script元素。 顺便说一句: local-name()返回上下文节点名称的本地部分 - 这不是你想要的。 编辑 因此,假设以下文档(请不要将代码作为链接发布!):
  • 在VS2015 / .NET Framework 4.5中, PresentationFramework程序WindowNonClientFrameThickness有一个SystemParameters类,它包含WindowNonClientFrameThickness和SmallIconWidth属性,因此等价物将是:
    我想这只是因为方法TryDequeue()有一个int类型的参数,即使你不使用它也必须给它一个。 I guess it's just because the method TryDequeue() has an parameter of type int, and you have to give it one even if you don't use it.
  • 我在代码中添加了一些注释,看看它是否有帮助: Northwnd db = new Northwnd("..."); try { // here we attempt to submit changes for the database // The ContinueOnConflict specifies that all updates to the // database should be tried, and that concurrency conflicts / ...
  • 我相信每个密钥都被分配了10个激活,而不考虑安装的同时或顺序。 如果10次激活已用完,可以联系Microsoft以请求其他密钥。 前一段时间(我最近没有检查过),msdn订阅者还可以访问各种“在线礼宾”聊天室。 虽然在聊天室工作的微软人员无法回答技术问题(显然,考虑到可能会提出的技术问题的广度),他们可以回答有关msdn订阅以及与软件相关的许可证和规则的真实问题。 根据协议,我问他们是否可以使用我的MSDN许可证密钥安装操作系统的副本来工作@home,例如 I believe that each key i ...
  • 你的问题是这个代码: Type.GetType("parminfo") 这将尝试查找具有完全限定名称 parminfo的类型,但没有这样的类型。 您的类在名称空间中声明,因此其完全限定名称为ConsoleApp.parminfo 。 更好的是,只需使用typeof(parminfo) 。 Your problem is this code: Type.GetType("parminfo") This will try to find a type with a fully qualified name ...
  • MSDN概述的模式是实现IDisposable的唯一正确方法,因为它将最终化考虑在内。 您需要仔细查看IDisposable实现: public void Dispose() { Dispose(true); // Use SupressFinalize in case a subclass // of this type implements a finalizer. GC.SuppressFinalize(this); } 这会调用您的dispose方法 ...
  • If SE_PRIVILEGE_REMOVED等于零,则将其定义为如此。 鉴于那里的定义,我建议零值意味着没有启用任何特权,或随后使用/删除:有,也从来没有任何令牌特权。 If SE_PRIVILEGE_REMOVED was equivalent to zero it would be defined as such. Given the definitions that are there, I would suggest that a zero values means no privileges h ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)