“用户”对象不支持索引 [英] 'User' object does not support indexing
本文介绍了“用户”对象不支持索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试克隆Twitter,这是我尝试发送推文时的问题。
I am trying to make twitter clone, and here is the problem when I am trying to send a tweet.
模型
class Tweet(models.Model):
text = models.CharField(max_length=140)
date = models.DateField(default=date.today)
user = models.ForeignKey(User, unique=True)
Form
class TweetForm(forms.ModelForm):
class Meta:
model = Tweet
exclude = ["user", 'date']
现在我正在尝试将User添加到tweet信息中手动,但出现错误:'User'对象不支持索引
And now I am trying to add User to tweet information mannualy, but get the error: 'User' object does not support indexing
这里是视图:
if request.method == 'POST':
form = TweetForm(request.POST)
# Have we been provided with a valid form?
if form.is_valid():
author = form.save(commit=False)
author.user = UserProfile.objects.get(request.user) #HERE ASIGNING THE USER
author.save()
如何明确地将用户分配给tweet?
How to corectly assign user to tweet?
推荐答案
只要您的 Author
模型类具有 AUTH_USER_MODEL
您正在使用的行(默认为 auth.User
)行:
As long as your Author
model class has a foreign key to the AUTH_USER_MODEL
you're using (the default is auth.User
) the line:
author.user = UserProfile.objects.get(request.user)
应为:
author.user = request.user
这篇关于“用户”对象不支持索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文