Python 如何在django中从用户模型中获取id

Python 如何在django中从用户模型中获取id,python,django,python-2.7,django-models,django-forms,Python,Django,Python 2.7,Django Models,Django Forms,我有以下代码: user=User.objects.get(username=uid) 我通过url“/profile/showprofile/{{post.author}”传递uid的值。我的post.author包含值为“dean88” 当运行表单并单击带有上述url的链接时。我得到一个错误,对基数为10“dean88”的int表示无效的文本 但是,当我转到Pythonshell并给出:user=user.objects.get(username='dean88')时,仍然会得到相同的错误

我有以下代码:

user=User.objects.get(username=uid)
我通过url“/profile/showprofile/{{post.author}”传递uid的值。我的post.author包含值为“dean88”

当运行表单并单击带有上述url的链接时。我得到一个错误,对基数为10“dean88”的int表示无效的文本

但是,当我转到Pythonshell并给出:user=user.objects.get(username='dean88')时,仍然会得到相同的错误。只有当我将用户id输入为整数时,错误才会出现。比如,user=user.objects.get(username=2)


问题可能是什么以及如何避免?

您当前正在为url kwarg获取一个“dean88”值,因为您正在向其传递post.author的字符串表示形式,即用户名。
改为使用“/profile/showprofile/{{post.author.pk}}”来传递实际的用户id。

您当前得到的url kwarg值为“dean88”,因为您传递的是post.author的字符串表示形式,即用户名。
改为使用“/profile/showprofile/{{post.author.pk}}”来传递实际的用户id。

是指django默认的
用户
模型吗?是。它指的是django的用户模型
dean88
看起来不像一个id,它是一个整数。尝试将其更改为
{{post.author.id}
在进一步阅读您的OP两次之后,我认为您一定创建了一个用户,该用户为
.username
属性分配了错误的值(也就是说,用户不是使用
dean88
创建的,而是使用
2
作为用户名。您可以通过管理界面进行检查,或者更好的方法是直接通过数据库数据上的
pgadmin
进行检查)
用户
您指的是django默认的
用户
模型吗?是的。它指的是django的用户模型
dean88
看起来不像是一个整数id。请尝试将其更改为
{post.author.id}
在进一步阅读您的OP两次之后,我认为您一定创建了将错误的值分配给
.username
属性的用户(即,用户不是使用
dean88
创建的,而是使用
2
作为用户名。您可以通过管理界面进行检查,或者更好的是直接通过数据库数据上的
pgadmin
进行检查)这也是我的假设(见我上面的评论)。但是,它并没有解释为什么
user=user.objects.get(username='dean88')
抛出一个错误,而
user=user.objects.get(username=2)
起作用。@Pynchia..code user=user.objects.get(username=2)在我的shell中不起作用。它抛出一个错误说:“对象名称不存在。用户匹配查询不存在”你是对的!我们需要看更多的代码才能弄清楚。很抱歉,我当时一定是误解了,我认为你的帖子缺少
这个词。很好,然后所有问题都解决了,就像我和@suselrd最初设想的那样,对吗?@suselrd..顺便说一句“/profile/showprofile”/{{post.author.pk}“这并没有返回任何值。仅当使用“/profile/showprofile/{{post.author.id}”时,它才将id返回到views.py。不知道为什么。对此有什么想法。这也是我的假设(请参阅我上面的评论)。但是,它没有解释为什么
user=user.objects.get(username='dean88'))
抛出一个错误,而
user=user.objects.get(username=2)
有效。@Pynchia..code user=user.objects.get(username=2)在我的shell中不起作用。它抛出一个错误,说“Object\u name不存在。用户匹配查询不存在。”“你是对的!我们需要看更多的代码来解决它。很抱歉,我当时一定是误解了,我认为你的帖子缺少
这个词。很好,然后所有问题都解决了,就像我和@suselrd最初假设的那样,对吗?@suselrd..顺便说一句“/profile/showprofile/{post.author.pk}”这不会返回任何值。只有使用时才可以。”“/profile/showprofile/{{post.author.id}}”它正在将id返回到views.py。不知道为什么。有什么想法吗。