变量无法为表达式 -- 在Django中扩展用户模型

0 投票
1 回答
3917 浏览
提问于 2025-04-16 08:52

我意识到有更优雅的方法来解决这个问题,我会慢慢找到的,但现在我只是先尝试让它能正常工作。最近我遇到了一个错误:

/accounts/profile/foobar/ 出现了语法错误
关键字不能是一个表达式(views.py,第104行)

这是出错的那一行。需要注意的是,关键字是我在网址中传递的一个字符串,我用它来查找用户。

user = User.objects.get(username=keyword)
up = UserProfile(user=user.id,
                 fullname=result['fullname'],
                 email=result['email'],
                 phone=result['phone'],
                 title=result['title'],
                 department=result['department'],
                 office=result['office'])

我是不是没有正确地将 UserProfile 对象映射到 User 对象?添加外键的正确方法是什么——直接传递对象本身吗?希望能得到一些见解和建议。

1 个回答

4

很容易复现这个问题:

>>> def foo(**kwargs):
...   return None
... 
>>> foo(a.b=1)
  File "<stdin>", line 1
SyntaxError: keyword can't be an expression

这个错误信息有点难懂——关键字在哪里呢?我猜这可能和 '.' 这个符号有关,因为它是用来获取属性的语法。

撰写回答